diff --git a/client/src/app/app-routing.module.ts b/client/src/app/app-routing.module.ts index 74be7602107e125b5080c172da80c49bede520ea..1843a44253dae02bdbed9f015391bc982f46c051 100644 --- a/client/src/app/app-routing.module.ts +++ b/client/src/app/app-routing.module.ts @@ -8,7 +8,6 @@ import { UserLoginFormComponent } from './users/user-login-form/user-login-form. import { UserProfileComponent } from './users/user-profile/user-profile.component'; import { UserGuestProfileComponent } from './users/user-guest-profile/user-guest-profile.component'; import { HomeComponent } from './home/home.component'; -import { UserProfileEditFormComponent } from './users/user-profile-edit-form/user-profile-edit-form.component'; const routes: Routes = [ @@ -21,7 +20,7 @@ const routes: Routes = [ { path: 'user/:id', component: UserGuestProfileComponent }, { path: 'profil', component: UserProfileComponent }, - { path: 'profil/rediger', component: UserProfileEditFormComponent}, + { path: 'profil/rediger', component: UserRegistrationFormComponent}, { path: 'register', component: UserRegistrationFormComponent }, { path: 'login', component: UserLoginFormComponent } ]; diff --git a/client/src/app/models/user.model.ts b/client/src/app/models/user.model.ts index 773c10040aace297acab374762af69d22329b4b9..0dac709fd1236f06ec2f5b4000bf0ff155c0c52e 100644 --- a/client/src/app/models/user.model.ts +++ b/client/src/app/models/user.model.ts @@ -9,6 +9,9 @@ export class User implements Deserializable, Serializable { private create_time: Date; private isAdmin: number; private location: string; + private firstName: string; + private lastName: string; + private mobileNo: string; constructor(input: any = null) { if (input) { @@ -21,6 +24,9 @@ export class User implements Deserializable, Serializable { this.create_time = new Date(); this.isAdmin = 0; this.location = null; + this.firstName = null; + this.lastName = null; + this.mobileNo = null; } } @@ -37,7 +43,10 @@ export class User implements Deserializable, Serializable { password: this.password, create_time: this.create_time, isAdmin: this.isAdmin, - location: this.location + location: this.location, + firstName: this.firstName, + lastName: this.lastName, + mobileNo: this.mobileNo }; } @@ -96,4 +105,28 @@ export class User implements Deserializable, Serializable { set setLocation(location: string){ this.location = location; } + + get getFirstName() { + return this.firstName; + } + + set setFirstName(firstName: string){ + this.firstName = firstName; + } + + get getLastName() { + return this.lastName; + } + + set setLastName(lastName: string){ + this.lastName = lastName; + } + + get getMobileNo() { + return this.mobileNo; + } + + set setMobileNo(mobileNo: string){ + this.mobileNo = mobileNo; + } } \ No newline at end of file diff --git a/client/src/app/posts/post-list/post-list.component.ts b/client/src/app/posts/post-list/post-list.component.ts index db23443e4c205cd1b30d47444c8ab6cc72c4078a..0577d19cd6ef42b89580814b9730ff4c5e005b78 100644 --- a/client/src/app/posts/post-list/post-list.component.ts +++ b/client/src/app/posts/post-list/post-list.component.ts @@ -80,7 +80,7 @@ export class PostListComponent implements OnInit { // Gets all posts by selected category await this.postService.getPostsByCategory(this.selectedCategory, this.selectedSort, this.priceMin, this.priceMax).then(posts => { - this.allPosts = posts; + this.allPosts = posts.filter((post: Post) => post.getStatus == 0); // Filter out closed post }).catch(error => { console.log(error); }); diff --git a/client/src/app/shared/select/select.component.scss b/client/src/app/shared/select/select.component.scss index 80d9dfbe8c869e198270566bb3c616e9d9f17b83..cb7eec1871426f6439ba7eb7fe7b17b07a42423e 100644 --- a/client/src/app/shared/select/select.component.scss +++ b/client/src/app/shared/select/select.component.scss @@ -1,4 +1,10 @@ +label{ + font-family: 'Josefin Sans', sans-serif; + font-size: 1.3rem; +} + select { + margin-top: 5px; padding: 15px 10px 15px 10px; font-family: 'Josefin Sans', sans-serif; font-size: 20px; diff --git a/client/src/app/users/user-guest-profile/user-guest-profile.component.html b/client/src/app/users/user-guest-profile/user-guest-profile.component.html index 82f48b038e5e275fe5fafda741a4aed188610f01..219fc762c8c3e0dd3978f45d5b535ad9d5892c68 100644 --- a/client/src/app/users/user-guest-profile/user-guest-profile.component.html +++ b/client/src/app/users/user-guest-profile/user-guest-profile.component.html @@ -14,9 +14,10 @@ <div class="titleWrapper"> <div class="img"></div> <div class="info"> - <p class="name">{{user.getUsername}}</p> + <p class="name">{{user.getFirstName}} {{user.getLastName}}</p> + <p class="username">{{user.getUsername}}</p> <p class="email">{{user.getEmail}}</p> - <p class="phone_number">+47 123 45 678</p> + <p class="phone_number">+47 {{user.getMobileNo}}</p> </div> </div> <div class="cardWrapper"> diff --git a/client/src/app/users/user-profile-edit-form/user-profile-edit-form.component.html b/client/src/app/users/user-profile-edit-form/user-profile-edit-form.component.html deleted file mode 100644 index 91aaccd0f010825ccd66e60ba09bc4c2c5b7d496..0000000000000000000000000000000000000000 --- a/client/src/app/users/user-profile-edit-form/user-profile-edit-form.component.html +++ /dev/null @@ -1,15 +0,0 @@ -<div class="registrationForm"> - <div class="cardWrapper"> - <h3>Rediger bruker</h3> - <div> - <app-input [(inputModel)]="username" label="Brukernavn" (blur)="checkForm()"></app-input> - <app-input [(inputModel)]="email" label="Epost" (blur)="checkForm()"></app-input> - <app-input type="password" [(inputModel)]="password" label="Passord" (blur)="checkForm()"></app-input> - <app-input type="password" [(inputModel)]="confirm_password" label="Bekreft passord" (blur)="checkForm()"></app-input> - <p class="status">{{statusMessage}}</p> - <app-button (click)="updateUser()" text="Lagre endringer"></app-button> - <app-button (click)="deleteUser()" text="Slett bruker"></app-button> - <a href="/profil"><app-button text="Tilbake til profil"></app-button></a> - </div> - </div> -</div> \ No newline at end of file diff --git a/client/src/app/users/user-profile-edit-form/user-profile-edit-form.component.scss b/client/src/app/users/user-profile-edit-form/user-profile-edit-form.component.scss deleted file mode 100644 index 2050a904fea4bbce0c70a3df1c7fba5b7c52828e..0000000000000000000000000000000000000000 --- a/client/src/app/users/user-profile-edit-form/user-profile-edit-form.component.scss +++ /dev/null @@ -1,35 +0,0 @@ -:host > .registrationForm { - padding: 5%; - display:flex; - justify-content: center; - margin-bottom: 50px; - h3 { - font-family: 'Josefin Sans', sans-serif; - font-size: 1.5rem; - font-weight: 500; - padding: 10px; - } - & > div.cardWrapper { - color: #fff; - display: flex; - flex-direction: column; - background: linear-gradient(90deg, #14A35A 0%, #24e072 100%); - padding: 10px; - width: 70%; - min-width: 300px; - max-width: 900px; - } -} -div.cardWrapper > div { - color: #000; - display: flex; - flex-direction: column; - background-color: #fff; - box-shadow: inset 0px 4px 4px rgb(0 0 0 / 50%); - gap: 10px; - padding: 20px 10px; -} -p.status { - margin: 10px 0 5px 5px; - font-style: italic; -} \ No newline at end of file diff --git a/client/src/app/users/user-profile-edit-form/user-profile-edit-form.component.spec.ts b/client/src/app/users/user-profile-edit-form/user-profile-edit-form.component.spec.ts deleted file mode 100644 index acaeb831344097d1a4cf13fcdd9de53b7724fab3..0000000000000000000000000000000000000000 --- a/client/src/app/users/user-profile-edit-form/user-profile-edit-form.component.spec.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { HttpClientTestingModule } from '@angular/common/http/testing'; -import { ComponentFixture, TestBed , fakeAsync} from '@angular/core/testing'; -import { RouterTestingModule } from '@angular/router/testing'; -import { Router } from '@angular/router'; -import { UserService } from '../user.service'; -import { SharedModule } from 'src/app/shared/shared.module'; -import { FormsModule } from '@angular/forms'; - -import { UserProfileEditFormComponent } from './user-profile-edit-form.component'; -import { UserProfileComponent } from '../user-profile/user-profile.component'; -import { User } from 'src/app/models/user.model'; -import { AuthService } from 'src/app/authentication/auth.service'; - -describe('UserProfileEditFormComponent', () => { - let component: UserProfileEditFormComponent; - let fixture: ComponentFixture<UserProfileEditFormComponent>; - let router: Router; - let mockUserService; - let mockAuthService; - - beforeEach(async () => { - // AuthService mock setup - mockAuthService = jasmine.createSpyObj(['getCurrentUser']); - mockAuthService.getCurrentUser.and.returnValue(new User({ - userId: 4, - username: "tester", - email: "test@test.com", - password: "1234", - create_time: 513498, - isAdmin: 0 - })); - - // UserService mock setup - mockUserService = jasmine.createSpyObj(['updateUser', 'deleteUser']); - mockUserService.updateUser.and.returnValue( - new Promise<string>( - (resolve) => { - resolve("success") - }) - ); - mockUserService.deleteUser.and.returnValue( - new Promise<any>( - (resolve) => { - resolve({data: []}) - }) - ); - }); - - - beforeEach(async () => { - await TestBed.configureTestingModule({ - declarations: [ UserProfileEditFormComponent ], - imports: [ - HttpClientTestingModule, - FormsModule, - SharedModule, - RouterTestingModule.withRoutes([ - { path: 'profil', component: UserProfileComponent} - ]) - ], - providers: [ - { provide: UserService, useValue: mockUserService }, - { provide: AuthService, useValue: mockAuthService }, - ] - }) - .compileComponents(); - }); - - beforeEach(() => { - fixture = TestBed.createComponent(UserProfileEditFormComponent); - component = fixture.componentInstance; - fixture.detectChanges(); - router = TestBed.inject(Router); - }); - - it('should validate form', async () => { - await fixture.whenStable(); - // Reset form - component.username = ""; - component.email = ""; - component.password = ""; - component.confirm_password = ""; - - // Tests all if-sentences in checkForm - expect(component.checkForm()).toBeFalse(); - expect(component.statusMessage).toBe("Brukernavn kan ikke være tom"); - - component.username = "Username"; - expect(component.checkForm()).toBeFalse(); - expect(component.statusMessage).toBe("Eposten kan ikke være tom"); - - component.email = "Email"; - expect(component.checkForm()).toBeFalse(); - expect(component.statusMessage).toBe("Passordet kan ikke være tomt"); - - component.password = "password"; - expect(component.checkForm()).toBeFalse(); - expect(component.statusMessage).toBe("Passordet kan ikke være tomt"); - - component.confirm_password = "hei"; - expect(component.checkForm()).toBeFalse(); - expect(component.statusMessage).toBe("Passordene gitt samsvarer ikke"); - - component.confirm_password = "password"; - expect(component.checkForm()).toBeTrue(); - expect(component.statusMessage).toBe(""); - }); - - it('should get current user', async () => { - expect(mockAuthService.getCurrentUser).toHaveBeenCalled(); - expect(component.user).toEqual(new User({ - userId: 4, - username: "tester", - email: "test@test.com", - password: "1234", - create_time: 513498, - isAdmin: 0 - })); - }); - - it('should not update invalid user', fakeAsync(() => { - // Reset form - component.username = ""; - component.email = ""; - component.password = ""; - component.confirm_password = ""; - // Tests that updating should not happen when user is invalid - component.updateUser(); - expect(component.statusMessage).toBe("Brukernavn kan ikke være tom"); - })); - - it('should route after updating user', async () => { - // Waits for ngOnInit and tests that url is changed after user is updated - await fixture.whenStable(); - component.username = "Username"; - component.email = "Email"; - component.password = "Password"; - component.confirm_password = "Password"; - component.updateUser(); - - expect(mockUserService.updateUser).toHaveBeenCalled(); - expect(router.url).toBe('/'); - }); - - it('should delete current user', async () => { - // Waits for ngOnInit and checks that we can delete the current user - await fixture.whenStable(); - component.deleteUser(); - expect(mockUserService.deleteUser).toHaveBeenCalledWith(4); - }); -}); diff --git a/client/src/app/users/user-profile-edit-form/user-profile-edit-form.component.ts b/client/src/app/users/user-profile-edit-form/user-profile-edit-form.component.ts deleted file mode 100644 index 6894c17223e7051e89e5fc6179351a5ddde1a51b..0000000000000000000000000000000000000000 --- a/client/src/app/users/user-profile-edit-form/user-profile-edit-form.component.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { Component, OnInit } from '@angular/core'; -import { AuthService } from 'src/app/authentication/auth.service'; -import { User } from 'src/app/models/user.model'; -import { UserService } from '../user.service'; -import { Router } from '@angular/router'; - -interface IUserLogin { - username: string; - password: string; -} - -@Component({ - selector: 'app-user-profile-edit-form', - templateUrl: './user-profile-edit-form.component.html', - styleUrls: ['./user-profile-edit-form.component.scss'] -}) -export class UserProfileEditFormComponent implements OnInit { - - constructor(private userService: UserService, private authService: AuthService, private router: Router) { } - - user: User = new User(); - username: string = ""; - email: string = ""; - password: string = ""; - confirm_password: string = ""; - - statusMessage: string = ""; - - ngOnInit(): void { - this.user = this.authService.getCurrentUser(); - - // Gets all user information and displays them in the component - if (this.user.getUserId !== 0) { - this.username = this.user.getUsername; - this.email = this.user.getEmail; - this.password = this.user.getPassword; - this.confirm_password = this.user.getPassword; - } else { - console.log("Error getting user information!"); - } - } - - /** - * Validates the form - */ - checkForm(): boolean { - if (this.username == "") { - this.setStatusMessage("Brukernavn kan ikke være tom"); - return false; - } - else if (this.email == "") { - this.setStatusMessage("Eposten kan ikke være tom"); - return false; - } - else if (this.password == "") { - this.setStatusMessage("Passordet kan ikke være tomt"); - return false; - } - else if (this.confirm_password == "") { - this.setStatusMessage("Passordet kan ikke være tomt"); - return false; - } - else if (this.confirm_password !== this.password) { - this.setStatusMessage("Passordene gitt samsvarer ikke"); - return false; - } - - this.setStatusMessage(""); - return true; - } - - /** - * Updates the user if given arguments are valid - */ - updateUser() { - if (this.checkForm()) { - const updatedUser = new User({ - username: this.username, - email: this.email, - password: this.password, - }); - const loginUser: IUserLogin = { - username: this.username, - password: this.password, - }; - // - // Updates user in database and redirects to the profile page afterwards - - this.userService.updateUser(updatedUser,this.user.getUserId).then(status => { - console.log("User was updated: " + JSON.stringify(status)); - this.authService.login(loginUser).then(() => - this.router.navigateByUrl("/profil") - ); - }).catch(error => { - console.log("Error updating user: " + error); - }); - } - } - - /** - * Sets the status message for user feedback on form submit - */ - setStatusMessage(message: string) { - this.statusMessage = message; - } - - /** - * Deletes user in database and navigates to login - */ - deleteUser() { - this.userService.deleteUser(this.user.getUserId).then(data => { - console.log("Successfully deleted user: " + this.user.getUserId); - this.authService.logout(); - this.router.navigateByUrl("/login"); - }).catch(error => { - console.log(error); - }); - } -} - - - - - diff --git a/client/src/app/users/user-profile/user-profile.component.html b/client/src/app/users/user-profile/user-profile.component.html index 842251d7940e76942f8b6094c501cf74effc4d64..dd02ed895f9ebddadcfdcd021b65aa918dc77de2 100644 --- a/client/src/app/users/user-profile/user-profile.component.html +++ b/client/src/app/users/user-profile/user-profile.component.html @@ -30,9 +30,10 @@ <div class="titleWrapper"> <div class="img"></div> <div class="info"> - <p class="name">{{user.getUsername}}</p> + <p class="name">{{user.getFirstName}} {{user.getLastName}}</p> + <p class="username">{{user.getUsername}}</p> <p class="email">{{user.getEmail}}</p> - <p class="phone_number">+47 123 45 678</p> + <p class="phone_number">+47 {{user.getMobileNo}}</p> </div> </div> <div class="cardWrapper"> diff --git a/client/src/app/users/user-registration-form/user-registration-form.component.html b/client/src/app/users/user-registration-form/user-registration-form.component.html index 06c00e23e10238a97fad560468ade1aad331b531..6fe14e6d785c3182fae39aaf2279eb9db74d3d9e 100644 --- a/client/src/app/users/user-registration-form/user-registration-form.component.html +++ b/client/src/app/users/user-registration-form/user-registration-form.component.html @@ -1,6 +1,6 @@ <div class="registrationForm"> <div class="cardWrapper"> - <h3>Registrer din profil</h3> + <h3>{{user?'Rediger profil':'Registrer bruker'}}</h3> <div> <div class="split"> <app-input class="splittedInput" [(inputModel)]="firstname" label="Fornavn" (blur)="checkForm()"></app-input> @@ -9,7 +9,7 @@ <app-input [(inputModel)]="username" label="Brukernavn" (blur)="checkForm()"></app-input> <app-input [(inputModel)]="email" label="Epost" (blur)="checkForm()"></app-input> <app-input [(inputModel)]="phone_number" label="Mobilnummer" (blur)="checkForm()"></app-input> - <app-select [(inputModel)]="location"> + <app-select [(inputModel)]="location" label="Fylke"> <option selected>Velg fylke . . .</option> <option>Agder</option> <option>Innlandet</option> @@ -26,7 +26,9 @@ <app-input [(inputModel)]="password" type="password" label="Passord" (blur)="checkForm()"></app-input> <app-input [(inputModel)]="confirm_password" type="password" label="Bekreft passord" (blur)="checkForm()"></app-input> <p class="status">{{statusMessage}}</p> - <app-button (click)="registerUser()" text="Registrer profil" class="btn pink"></app-button> + <app-button (click)="registerUser()" [text]="user?'Lagre endringer':'Registrer profil'" class="btn pink"></app-button> + + <app-button *ngIf="user" (click)="deleteUser()" text="Slett bruker"></app-button> </div> </div> </div> \ No newline at end of file diff --git a/client/src/app/users/user-registration-form/user-registration-form.component.ts b/client/src/app/users/user-registration-form/user-registration-form.component.ts index f25cac2c21b561a15add323483c7c311783adf0f..0402e6e1b56dac1839256c5b80a00af21d2d94d7 100644 --- a/client/src/app/users/user-registration-form/user-registration-form.component.ts +++ b/client/src/app/users/user-registration-form/user-registration-form.component.ts @@ -4,6 +4,11 @@ import { AuthService } from 'src/app/authentication/auth.service'; import { User } from 'src/app/models/user.model'; import { UserService } from '../user.service'; +interface IUserLogin { + username: string; + password: string; +} + @Component({ selector: 'app-user-registration-form', templateUrl: './user-registration-form.component.html', @@ -21,9 +26,20 @@ export class UserRegistrationFormComponent implements OnInit { statusMessage: string = ""; + user: User = null; + constructor(private userService: UserService, private authService: AuthService, private router: Router) { } ngOnInit(): void { + if (this.router.url == "/profil/rediger") { + this.user = this.authService.getCurrentUser(); + this.username = this.user.getUsername; + this.email = this.user.getEmail; + this.location = this.user.getLocation; + this.firstname = this.user.getFirstName; + this.lastname = this.user.getLastName; + this.phone_number = this.user.getMobileNo; + } } /** @@ -76,21 +92,52 @@ export class UserRegistrationFormComponent implements OnInit { */ registerUser() { if (this.checkForm()) { - const newUser = new User({ - username: this.username, - email: this.email, - password: this.password, - isAdmin: 0, - location: this.location - }); - - // Adds user to database and redirects to the homepage afterwards - this.authService.registerUser(newUser).then(status => { - console.log("User was added: " + JSON.stringify(status)); - this.router.navigateByUrl("/login"); - }).catch(error => { - console.log("Error adding user: " + error); - }); + if (this.user) { + // Update user + const updatedUser = new User({ + username: this.username, + email: this.email, + password: this.password, + location: this.location, + firstName: this.firstname, + lastName: this.lastname, + mobileNo: this.phone_number + }); + const loginUser: IUserLogin = { + username: this.username, + password: this.password, + }; + // Updates user in database and redirects to the profile page afterwards + + this.userService.updateUser(updatedUser, this.user.getUserId).then(status => { + console.log("User was updated: " + JSON.stringify(status)); + this.authService.login(loginUser).then(() => + this.router.navigateByUrl("/profil") + ); + }).catch(error => { + console.log("Error updating user: " + error); + }); + } else { + // New user + const newUser = new User({ + username: this.username, + email: this.email, + password: this.password, + isAdmin: 0, + location: this.location, + firstName: this.firstname, + lastName: this.lastname, + mobileNo: this.phone_number + }); + + // Adds user to database and redirects to the homepage afterwards + this.authService.registerUser(newUser).then(status => { + console.log("User was added: " + JSON.stringify(status)); + this.router.navigateByUrl("/login"); + }).catch(error => { + console.log("Error adding user: " + error); + }); + } } } @@ -100,4 +147,17 @@ export class UserRegistrationFormComponent implements OnInit { setStatusMessage(message: string) { this.statusMessage = message; } + + /** + * Deletes user in database and navigates to login + */ + deleteUser() { + this.userService.deleteUser(this.user.getUserId).then(data => { + console.log("Successfully deleted user: " + this.user.getUserId); + this.authService.logout(); + this.router.navigateByUrl("/login"); + }).catch(error => { + console.log(error); + }); + } } diff --git a/client/src/app/users/user.module.ts b/client/src/app/users/user.module.ts index 1eb33f9f6e76a708bd456704d8a9b4c0385e1304..902d1d0acae92931bc203f6b59a3091a8527d68c 100644 --- a/client/src/app/users/user.module.ts +++ b/client/src/app/users/user.module.ts @@ -7,7 +7,6 @@ import { UserRegistrationFormComponent } from './user-registration-form/user-reg import { UserProfileComponent } from './user-profile/user-profile.component'; import { UserLoginFormComponent } from './user-login-form/user-login-form.component'; import { UserGuestProfileComponent } from './user-guest-profile/user-guest-profile.component'; -import { UserProfileEditFormComponent } from './user-profile-edit-form/user-profile-edit-form.component'; import { UserReviewDetailComponent } from './user-review-detail/user-review-detail.component'; @@ -18,7 +17,6 @@ import { UserReviewDetailComponent } from './user-review-detail/user-review-deta UserProfileComponent, UserLoginFormComponent, UserGuestProfileComponent, - UserProfileEditFormComponent, UserReviewDetailComponent ], imports: [ diff --git a/server/src/controllers/authController/index.ts b/server/src/controllers/authController/index.ts index 8f855f61f2e433b5a0e9de785c2800630c68808f..f4624b2ceb08690ec80c337414e12388e3a13647 100644 --- a/server/src/controllers/authController/index.ts +++ b/server/src/controllers/authController/index.ts @@ -10,7 +10,7 @@ const router = express.Router(); // Post register user `/api/auth/register` router.route('/register').post(async (request: Request, response: Response) => { - const {username, email, password, isAdmin, location, create_time} = request.body; + const {username, email, password, isAdmin, location, firstName, lastName, mobileNo, create_time} = request.body; try { // Check valid request data parameters const user_data: IUser = { @@ -18,18 +18,21 @@ router.route('/register').post(async (request: Request, response: Response) => { "email": email, "password": password, "isAdmin": isAdmin || 0, - "location": location || null + "location": location || null, + "firstName": firstName, + "lastName": lastName, + "mobileNo": mobileNo }; if (Object.values(user_data).filter(p => p == undefined).length > 0) return response.status(500).send("Error"); // Check for user duplicates - const duplicate_input = "SELECT userId, username, email, create_time, isAdmin FROM user WHERE username=? AND password=?;" + const duplicate_input = "SELECT userId, username, email, create_time, mobileNo, isAdmin FROM user WHERE username=? AND password=?;" const user = await query(duplicate_input,[user_data.username, user_data.password]); const retrievedUserObj = Object.values(JSON.parse(JSON.stringify(user.data)))[0]; if (retrievedUserObj) { return response.status(403).send("There exists an user with the same username or emails given!"); } // If there is no duplicates, create new user - const input = (`INSERT INTO user(username, email, password, isAdmin, location) VALUES (?,?,?,?,?)`) + const input = (`INSERT INTO user(username, email, password, isAdmin, location, firstName, lastName, mobileNo) VALUES (?,?,?,?,?,?,?,?)`) return response.status(200).json( await query(input,Object.values(user_data)) ); @@ -42,7 +45,7 @@ router.route('/register').post(async (request: Request, response: Response) => { router.route('/login').post(async (request: Request, response: Response) => { const {username, password} = request.body; try { - const input = "SELECT userId, username, email, isAdmin, create_time, location FROM user WHERE username=? AND password=?;" + const input = "SELECT userId, username, email, isAdmin, firstName, lastName, mobileNo, create_time, location FROM user WHERE username=? AND password=?;" const user = await query(input,[username, password]); // Check if an user object is retrieved const userObj = Object.values(JSON.parse(JSON.stringify(user.data)))[0]; diff --git a/server/src/controllers/postController/index.ts b/server/src/controllers/postController/index.ts index 1fa7f55363dfe125abe0cfd5204f70dea521f5ae..aacd920ea79c4e0b3445e231bc221a8b9dddfcab 100644 --- a/server/src/controllers/postController/index.ts +++ b/server/src/controllers/postController/index.ts @@ -150,10 +150,10 @@ router.route("/").get(async (request: Request, response: Response) => { router.route("/max").get(async (request: Request, response: Response) => { const { categoryid } = request.query as { [key: string]: string }; try { - let input = `SELECT MAX(p.price) as maxPrice FROM post as p `; + let input = `SELECT MAX(p.price) as maxPrice FROM post as p WHERE p.status=0`; if (categoryid && categoryid != "undefined" && categoryid != "0") { - input += `WHERE p.categoryid=?`; + input += ` AND p.categoryid=?`; } response.status(200).json(await query(input, [categoryid])); diff --git a/server/src/controllers/userController/index.ts b/server/src/controllers/userController/index.ts index 4586bc6bdf79213a5b914fc7330a70dbaad0d7ac..b14a65903c70461dd342a67aa9f6dbbc28eb905c 100644 --- a/server/src/controllers/userController/index.ts +++ b/server/src/controllers/userController/index.ts @@ -8,17 +8,20 @@ const router = express.Router(); /* ============================= CREATE ============================= */ // Create an user `/api/user/` router.route('/').post(async (request: Request, response: Response) => { - const {username, email, password, isAdmin, location, create_time} = request.body; // destructuring + const {username, email, password, isAdmin, location, firstName, lastName, mobileNo, create_time} = request.body; // destructuring try { const user: IUser = { "username": username, "email": email, "password": password, "isAdmin": isAdmin || 0, - "location": location || null + "location": location || null, + "firstName": firstName, + "lastName": lastName, + "mobileNo": mobileNo }; if (Object.values(user).filter(p => p == undefined).length > 0) return response.status(500).send("Error"); - const input = (`INSERT INTO user(username, email, password, isAdmin, location) VALUES (?,?,?,?,?)`); + const input = (`INSERT INTO user(username, email, password, isAdmin, location, firstName, lastName, mobileNo) VALUES (?,?,?,?,?,?,?,?)`); return response.status(200).json( await query(input, Object.values(user)) ); @@ -41,7 +44,7 @@ router.route('/').get(async (_: Request, response: Response) => { router.route('/:userId').get(async (request: Request, response: Response) => { const userId = request.params.userId; try { - const input = `SELECT userId, username, email, create_time, location FROM user WHERE userId=?;` + const input = `SELECT userId, username, email, create_time, location, firstName, lastName, mobileNo FROM user WHERE userId=?;` response.status(200).json(await query(input,[userId])); } catch (error) { response.status(400).send("Bad Request"); @@ -52,10 +55,10 @@ router.route('/:userId').get(async (request: Request, response: Response) => { // Update user from id `/api/user/:userId` router.route('/:userId').put(async (request: Request, response: Response) => { const userId = parseInt(request.params.userId); - const {username, email, password} = request.body; + const {username, email, password, location, firstName, lastName, mobileNo} = request.body; try { - const input = `UPDATE user SET username=?, email=?, password=? WHERE userId=?;`; - response.status(200).json(await query(input,[username, email, password, userId])); + const input = `UPDATE user SET username=?, email=?, password=?, location=?, firstName=?, lastName=?, mobileNo=? WHERE userId=?;`; + response.status(200).json(await query(input,[username, email, password, location, firstName, lastName, mobileNo, userId])); } catch (error) { console.error(error); response.status(400).send("Bad Request"); diff --git a/server/src/models/user.ts b/server/src/models/user.ts index 041f4e521261456476596b4ade95202fe509454c..f963f05a8332afdc14e7ddd5848170a1fdbf046e 100644 --- a/server/src/models/user.ts +++ b/server/src/models/user.ts @@ -7,6 +7,9 @@ interface IUser{ create_time?: Date; isAdmin: number; location: string; + firstName: string; + lastName: string; + mobileNo: string; } export default IUser;