Skip to content
Snippets Groups Projects
Commit 8f5edaba authored by Ethan Allen-Harris's avatar Ethan Allen-Harris
Browse files

Merge branch 'develop' into 'issueThirtySix'

merge

See merge request !101
parents a3bfde8f 3ba4e288
No related branches found
No related tags found
3 merge requests!114LoggingService service class, new method to add a log to the "Logs" table when...,!108merge,!101merge
Showing
with 675 additions and 87 deletions
package com.example.clientproject.data.events;
import com.example.clientproject.data.logs.Logs;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.Set;
/**
* Entity object for events which trigger a log
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Events {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long eventId;
private String eventName;
@OneToMany(cascade=CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name="Event_Id", nullable = false)
private Set<Logs> logs;
}
package com.example.clientproject.data.events;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.Optional;
/**
* Repository for the "Events" Entity
*/
public interface EventsRepo extends JpaRepository<Events, Long> {
/**
* Find an event by its name
* @param name - the name to search by
* @return - the event as an optional
*/
@Query("select e from Events e where e.eventName = ?1")
Optional<Events> findByEventName(String name);
}
package com.example.clientproject.data.logs;
import com.example.clientproject.data.converters.TinyIntToBoolean;
import com.example.clientproject.data.events.Events;
import com.example.clientproject.data.users.Users;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
/**
* Entity object for logs
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Logs {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long logId;
private String logDetails;
private String logDateTime;
@Convert(converter = TinyIntToBoolean.class)
private boolean logSuperAdmin;
@ManyToOne
@JoinColumn(name="User_Id", nullable=false)
private Users user;
@ManyToOne
@JoinColumn(name="Event_Id", nullable=false)
private Events event;
public Logs(String details, String dateTime, boolean superAdmin, Users aUser, Events aEvent) {
logDetails = details;
logDateTime = dateTime;
logSuperAdmin = superAdmin;
user = aUser;
event = aEvent;
}
}
package com.example.clientproject.data.logs;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
/**
* JPA Repo for the Logs entity
*/
public interface LogsRepo extends JpaRepository<Logs, Long> {
/**
* Find all the logs from a specific date time
* @param dateTime - the datetime to search by
* @return - list of logs from that date time
*/
@Query("select l from Logs l where l.logDateTime like ?1")
List<Logs> findByDateTime(String dateTime);
/**
* Find all the logs for a specific event
* @param eventId - the id of the event to search by
* @return - a list of logs with that event
*/
@Query("select l from Logs l where l.event.eventId = ?1")
List<Logs> findByEventId(long eventId);
/**
* Find all the logs for a specific user
* @param userId - the id of the user to search by
* @return - a list of all the logs for that user
*/
@Query("select l from Logs l where l.user.userId = ?1")
List<Logs> findByUserId(long userId);
/**
* Find all the logs by a specific super admin status
* @param superAdminStatus - the status to search by
* @return - a list of the logs found
*/
@Query("select l from Logs l where l.logSuperAdmin = ?1")
List<Logs> findBySuperAdminStatus(boolean superAdminStatus);
}
package com.example.clientproject.data.users;
import com.example.clientproject.data.logs.Logs;
import com.example.clientproject.data.shops.Shops;
import com.example.clientproject.data.userStampBoards.UserStampBoards;
import com.example.clientproject.data.tags.Tags;
......@@ -91,6 +92,10 @@ public class Users {
)
private List<Tags> favouriteTags;
@OneToMany(cascade=CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name="User_Id", nullable=false)
private Set<Logs> logs;
public String toString(){
return "User:" + this.getUserFirstName();
}
......
package com.example.clientproject.service;
import com.example.clientproject.data.events.Events;
import com.example.clientproject.data.logs.Logs;
import com.example.clientproject.data.logs.LogsRepo;
import com.example.clientproject.service.Utils.JWTUtils;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* Service for all logging based methods
*/
@Service
public class LoggingService {
LogsRepo logsRepo;
JWTUtils jwtUtils;
/**
* Constructor
* @param aLogsRepo - object of type LogsRepo
* @param aJWTUtils - object of type JWTUtils
*/
public LoggingService(LogsRepo aLogsRepo, JWTUtils aJWTUtils) {
jwtUtils = aJWTUtils;
logsRepo = aLogsRepo;
}
/**
* Method for logging an event
* @param event - the event
* @param session - the session
* @param details - details of the event
*/
public void logEvent(Events event, HttpSession session, String details) {
// Instantiate a flagging variable
boolean superAdminStatus;
// If the session attribute "superAdmin" doesn't exist (super admin not logged in)
if (session.getAttribute("superAdmin") == null) {
// Set the flag to false
superAdminStatus = false;
// Else
} else {
// Set the flag to the state of the session attribute
superAdminStatus = (boolean) session.getAttribute("superAdmin");
}
// Instantiate a DateTimeFormatter with the correct format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// Create a new Log object
Logs newLog = new Logs(
details,
LocalDateTime.now().format(formatter),
superAdminStatus,
jwtUtils.getLoggedInUserRow(session).get(),
event
);
// Save the new log
logsRepo.save(newLog);
}
}
package com.example.clientproject.service.Utils;
import com.example.clientproject.data.userPermissions.UserPermissions;
import com.example.clientproject.data.userPermissions.UserPermissionsRepo;
import com.example.clientproject.data.users.Users;
import com.example.clientproject.data.users.UsersRepo;
import io.jsonwebtoken.Claims;
......@@ -23,9 +25,11 @@ import java.util.Optional;
public class JWTUtils {
private UsersRepo usersRepo;
private UserPermissionsRepo userPermRepo;
public JWTUtils(UsersRepo ausersRepo){
usersRepo = ausersRepo;
public JWTUtils(UsersRepo aUsersRepo, UserPermissionsRepo aUserPermsRepo){
usersRepo = aUsersRepo;
userPermRepo = aUserPermsRepo;
}
private String SECRET_KEY;
......@@ -91,6 +95,14 @@ public class JWTUtils {
jwtTimeToLive // used to calculate expiration (claim = exp)
);
List<UserPermissions> userPermList = userPermRepo.findByUserId(userId);
for (UserPermissions u: userPermList) {
if (u.getAdminType().getAdminTypeId() == 3) {
setSuperAdmin(session, true);
break;
}
}
session.setAttribute("loginCredJWT", jwt);
return jwt.toString();
}
......@@ -131,6 +143,14 @@ public class JWTUtils {
}
public void logOutUser(HttpSession session){
if ((boolean) session.getAttribute("superAdmin")) {
setSuperAdmin(session, false);
}
session.removeAttribute("loginCredJWT");
}
public void setSuperAdmin(HttpSession session, boolean status) {
session.setAttribute("superAdmin", status);
}
}
This diff is collapsed.
......@@ -3,7 +3,9 @@ import random
import hashlib
global current_user_id
current_user_id = 2
global current_stamp_id
current_stamp_id = 1
current_user_id = 1
# Where pos = position on line, total = total elements in line, fileName is the file name and concat is to remove some
# random text from surnames.csv
......@@ -37,6 +39,31 @@ def createInsert(data, table, columns):
tempString = 'INSERT INTO ' + table + " (" + columns + ")" + ' VALUES ' + '(' + data + ');'
return tempString
def createStampBoard():
query = '10,"#ff0000","stamp.png"'
return createInsert(query, "Stamp_Boards", "Stamp_Board_Size, Stamp_Board_Colour, Stamp_Board_Icon")
def createRewards():
global current_stamp_id
rewardsArray = ['"10% off"','"5% off"','"2 for 1"','"£5 off"']
query = rewardsArray[random.randint(0,len(rewardsArray)-1)] + ',' + str(random.randint(3,10)) + ',' + str(current_stamp_id+1)
return createInsert(query, "Rewards", "Reward_Name, Reward_Stamp_Location, Stamp_Board_Id")
def linkTags(shopId):
finalArray = []
randomNo = random.randint(1,19)
tagIdArray = []
for i in range(1,20):
tagIdArray.append(i)
random.shuffle(tagIdArray)
for i in range(1, randomNo):
finalArray.append(createInsert((str(shopId) + ',' + str(tagIdArray[i])),"Shop_Tag_Links","Shop_Id, Tag_Id"))
return finalArray
# Where amount is how many names to compile, and usertype is the type of user you'd like to generate (1,2,3)
#
# Returns a list of complete insert statements
......@@ -66,11 +93,11 @@ def namePopulator(amount, userType):
for i in range(0, amount):
twoFAMethod = random.randint(1, 2)
email = newForenames[i] + newSurnames[i] + "@email.com"
stringInsert = '"' + newForenames[i] + '","' + newSurnames[i] + '","' + email + '","' + stdPassword + '","' + profilePic + '",' + str(twoFAMethod)
stringInsert = '"' + newForenames[i].lower() + '","' + newSurnames[i].lower() + '","' + email.lower() + '","' + stdPassword + '","' + profilePic + '",' + str(twoFAMethod)
insertArray.append(createInsert(stringInsert, "Users", "User_First_Name, User_Last_Name, User_Email, User_Password, User_Profile_Picture, Two_Factor_Method_Id"))
tempAmount = current_user_id
while current_user_id < (tempAmount+amount-1):
while current_user_id < (tempAmount+amount):
# print(current_user_id)
# print(current_user_id+amount)
stringInsert = str(current_user_id) + ',' + '1' + ',' + str(userType)
......@@ -115,8 +142,8 @@ def companyPopulator(amount):
countryi = random.randint(0, len(countries)-1)
stringInsert = '"' + companyNames[i] + '","' + "" + '","' + websiteArray[i] + '","' + str(earnings) + '","' + countries[countryi] + '","' + "shopPic.png" + '",' + str(random.randint(0, 1)) + ',' + str(1)
insertArray.append(createInsert(stringInsert, "Shops", "Shop_Name, Shop_Description, Shop_Website, Shop_Earnings, Shop_Countries, Shop_Image, Shop_Active, Stamp_Board_Id"))
stringInsert = '"' + companyNames[i] + '","' + "" + '","' + websiteArray[i].lower() + '","' + str(earnings) + '","' + countries[countryi].lower() + '","' + "shopPic.png" + '","' +"shopBanner.png" + '",' + str(random.randint(0, 1)) + ',' + str(i+2) + ',' + str(random.randint(2,7))
insertArray.append(createInsert(stringInsert, "Shops", "Shop_Name, Shop_Description, Shop_Website, Shop_Earnings, Shop_Countries, Shop_Image, Shop_Banner, Shop_Active, Stamp_Board_Id, Category_Id"))
return insertArray
......@@ -133,6 +160,7 @@ def userWriter(f, amount, userType):
# Generates sql and writes to file
def createSQLscript():
global current_stamp_id
f = open("script.sql", "r+")
f.truncate()
f.close()
......@@ -152,13 +180,30 @@ def createSQLscript():
f.write("\n\n")
# Shops
amount = int(input("How many shops would you like to generate?: "))
# Stamp Boards
for i in range(0,amount):
f.write(createStampBoard())
f.write("\n")
f.write(createRewards())
f.write("\n")
current_stamp_id+=1
# Shops
companies = companyPopulator(amount)
for each in companies:
f.write(each)
f.write("\n")
# Tags
tagLinkArray = []
for i in range(1, amount+1):
tagLinkArray = linkTags(i)
for i in range(0,len(tagLinkArray)):
f.write(tagLinkArray[i])
f.write("\n")
f.close()
......
src/main/resources/database/WeekFourERD.png

86.2 KiB

......@@ -255,6 +255,41 @@ CREATE TABLE IF NOT EXISTS `mydb`.`Socials` (
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`Events`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Events` (
`Event_Id` INT NOT NULL AUTO_INCREMENT,
`Event_Name` VARCHAR(45) NOT NULL,
PRIMARY KEY(`Event_Id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`Logs`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Logs` (
`Log_Id` INT NOT NULL AUTO_INCREMENT,
`Event_Id` INT NOT NULL,
`User_Id` INT NOT NULL,
`Log_Details` VARCHAR(150) NOT NULL,
`Log_Date_Time` DATETIME NOT NULL,
`Log_Super_Admin` TINYINT NOT NULL,
PRIMARY KEY(`Log_Id`, `Event_Id`, `User_Id`),
CONSTRAINT `fk_Events1`
FOREIGN KEY (`Event_Id`)
REFERENCES `mydb`.`Events` (`Event_Id`)
ON UPDATE NO ACTION
ON DELETE NO ACTION,
CONSTRAINT `fk_Users1`
FOREIGN KEY (`User_Id`)
REFERENCES `mydb`.`Users` (`User_Id`)
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
ENGINE = InnoDB;
INSERT INTO two_factor_methods (`Two_Factor_Method_Id`, `Two_Factor_Method_Name`) VALUES (1, 'None');
......@@ -276,22 +311,35 @@ INSERT INTO Admin_Types (Admin_Type_Id, Admin_Type_Name) VALUES (1,'User');
INSERT INTO Admin_Types (Admin_Type_Id, Admin_Type_Name) VALUES (2,'Business Admin');
INSERT INTO Admin_Types (Admin_Type_Id, Admin_Type_Name) VALUES (3,'Super Admin');
INSERT INTO Tags (Tag_Name) VALUES ('Football');
INSERT INTO Tags (Tag_Name) VALUES ('Fashion');
INSERT INTO Tags (Tag_Name) VALUES ('Electronics');
INSERT INTO Tags (Tag_Name) VALUES ('Coffee');
INSERT INTO Tags (Tag_Name) VALUES ('Art');
INSERT INTO Tags (Tag_Name) VALUES ('Pets');
INSERT INTO Tags (Tag_Name) VALUES ('Clothes');
INSERT INTO Tags (Tag_Name) VALUES ('Designer');
INSERT INTO Tags (Tag_Name) VALUES ('Groceries');
INSERT INTO Tags (Tag_Name) VALUES ('Cars');
INSERT INTO Tags (Tag_Name) VALUES ('Hiking');
INSERT INTO Tags (Tag_Name) VALUES ('Cooking');
INSERT INTO Tags (Tag_Name) VALUES ('Furniture');
INSERT INTO Tags (Tag_Name) VALUES ('Gaming');
INSERT INTO Tags (Tag_Name) VALUES ('Travelling');
INSERT INTO Tags (Tag_Name) VALUES ('Beauty');
INSERT INTO Tags (Tag_Name) VALUES ('Eco-friendly');
INSERT INTO Tags (Tag_Name) VALUES ('Decorations');
INSERT INTO Tags (Tag_Name) VALUES ('Photography');
INSERT INTO Tags (Tag_Name) VALUES ('football');
INSERT INTO Tags (Tag_Name) VALUES ('fashion');
INSERT INTO Tags (Tag_Name) VALUES ('electronics');
INSERT INTO Tags (Tag_Name) VALUES ('coffee');
INSERT INTO Tags (Tag_Name) VALUES ('art');
INSERT INTO Tags (Tag_Name) VALUES ('pets');
INSERT INTO Tags (Tag_Name) VALUES ('clothes');
INSERT INTO Tags (Tag_Name) VALUES ('designer');
INSERT INTO Tags (Tag_Name) VALUES ('groceries');
INSERT INTO Tags (Tag_Name) VALUES ('cars');
INSERT INTO Tags (Tag_Name) VALUES ('hiking');
INSERT INTO Tags (Tag_Name) VALUES ('cooking');
INSERT INTO Tags (Tag_Name) VALUES ('furniture');
INSERT INTO Tags (Tag_Name) VALUES ('gaming');
INSERT INTO Tags (Tag_Name) VALUES ('travelling');
INSERT INTO Tags (Tag_Name) VALUES ('beauty');
INSERT INTO Tags (Tag_Name) VALUES ('eco-friendly');
INSERT INTO Tags (Tag_Name) VALUES ('decorations');
INSERT INTO Tags (Tag_Name) VALUES ('photography');
INSERT INTO Events (Event_Name) VALUES ('New Account Created');
INSERT INTO Events (Event_Name) VALUES ('Failed Login');
INSERT INTO Events (Event_Name) VALUES ('Successful Login');
INSERT INTO Events (Event_Name) VALUES ('User Details Changed');
INSERT INTO Events (Event_Name) VALUES ('User Removed');
INSERT INTO Events (Event_Name) VALUES ('New Shop');
INSERT INTO Events (Event_Name) VALUES ('Deleted Shop');
INSERT INTO Events (Event_Name) VALUES ('New Favourite Business');
INSERT INTO Events (Event_Name) VALUES ('New Shop User');
INSERT INTO Events (Event_Name) VALUES ('Shop Details Changed');
INSERT INTO Events (Event_Name) VALUES ('Shop Activity Toggled');
INSERT INTO Events (Event_Name) VALUES ('Image Inserted');
\ No newline at end of file
......@@ -265,6 +265,40 @@ CREATE TABLE IF NOT EXISTS `User_Stamp_Boards` (
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Events`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Events` (
`Event_Id` INT NOT NULL AUTO_INCREMENT,
`Event_Name` VARCHAR(45) NOT NULL,
PRIMARY KEY(`Event_Id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Logs`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Logs` (
`Log_Id` INT NOT NULL AUTO_INCREMENT,
`Event_Id` INT NOT NULL,
`User_Id` INT NOT NULL,
`Log_Details` VARCHAR(150),
`Log_Date_Time` DATETIME NOT NULL,
`Log_Super_Admin` TINYINT NOT NULL,
PRIMARY KEY(`Log_Id`, `Event_Id`, `User_Id`),
CONSTRAINT `fk_Events1`
FOREIGN KEY (`Event_Id`)
REFERENCES `Events` (`Event_Id`)
ON UPDATE NO ACTION
ON DELETE NO ACTION,
CONSTRAINT `fk_Users1`
FOREIGN KEY (`User_Id`)
REFERENCES `Users` (`User_Id`)
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
ENGINE = InnoDB;
INSERT INTO two_factor_methods (`Two_Factor_Method_Id`, `Two_Factor_Method_Name`) VALUES (1, 'None');
INSERT INTO two_factor_methods (`Two_Factor_Method_Id`, `Two_Factor_Method_Name`) VALUES (2, 'GAuth');
......@@ -284,4 +318,35 @@ INSERT INTO Admin_Types (Admin_Type_Id, Admin_Type_Name) VALUES (1,'User');
INSERT INTO Admin_Types (Admin_Type_Id, Admin_Type_Name) VALUES (2,'Business Admin');
INSERT INTO Admin_Types (Admin_Type_Id, Admin_Type_Name) VALUES (3,'Super Admin');
INSERT INTO Tags (Tag_Name) VALUES ('Football');
\ No newline at end of file
INSERT INTO Tags (Tag_Name) VALUES ('football');
INSERT INTO Tags (Tag_Name) VALUES ('fashion');
INSERT INTO Tags (Tag_Name) VALUES ('electronics');
INSERT INTO Tags (Tag_Name) VALUES ('coffee');
INSERT INTO Tags (Tag_Name) VALUES ('art');
INSERT INTO Tags (Tag_Name) VALUES ('pets');
INSERT INTO Tags (Tag_Name) VALUES ('clothes');
INSERT INTO Tags (Tag_Name) VALUES ('designer');
INSERT INTO Tags (Tag_Name) VALUES ('groceries');
INSERT INTO Tags (Tag_Name) VALUES ('cars');
INSERT INTO Tags (Tag_Name) VALUES ('hiking');
INSERT INTO Tags (Tag_Name) VALUES ('cooking');
INSERT INTO Tags (Tag_Name) VALUES ('furniture');
INSERT INTO Tags (Tag_Name) VALUES ('gaming');
INSERT INTO Tags (Tag_Name) VALUES ('travelling');
INSERT INTO Tags (Tag_Name) VALUES ('beauty');
INSERT INTO Tags (Tag_Name) VALUES ('eco-friendly');
INSERT INTO Tags (Tag_Name) VALUES ('decorations');
INSERT INTO Tags (Tag_Name) VALUES ('photography');
INSERT INTO Events (Event_Name) VALUES ('New Account Created');
INSERT INTO Events (Event_Name) VALUES ('Failed Login');
INSERT INTO Events (Event_Name) VALUES ('Successful Login');
INSERT INTO Events (Event_Name) VALUES ('User Details Changed');
INSERT INTO Events (Event_Name) VALUES ('User Removed');
INSERT INTO Events (Event_Name) VALUES ('New Shop');
INSERT INTO Events (Event_Name) VALUES ('Deleted Shop');
INSERT INTO Events (Event_Name) VALUES ('New Favourite Business');
INSERT INTO Events (Event_Name) VALUES ('New Shop User');
INSERT INTO Events (Event_Name) VALUES ('Shop Details Changed');
INSERT INTO Events (Event_Name) VALUES ('Shop Activity Toggled');
INSERT INTO Events (Event_Name) VALUES ('Image Inserted');
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment