Commit f40cbcd3 by Ooh-Ao

login

parent a77f8b77
...@@ -59,30 +59,30 @@ User.beforeUpdate(async (user, options) => { ...@@ -59,30 +59,30 @@ User.beforeUpdate(async (user, options) => {
} }
}); });
(async () => { // (async () => {
try { // try {
// sync() จะสร้างตารางตาม Model ทั้งหมดที่มีในโปรเจกต์ (ถ้ายังไม่มี) // // sync() จะสร้างตารางตาม Model ทั้งหมดที่มีในโปรเจกต์ (ถ้ายังไม่มี)
// หากมีอยู่แล้วและต้องการ drop table เดิมให้ใช้ force: true (ไม่แนะนำบน production) // // หากมีอยู่แล้วและต้องการ drop table เดิมให้ใช้ force: true (ไม่แนะนำบน production)
await sequelize.sync({ force: false }); // await sequelize.sync({ force: false });
console.log("Table(s) created successfully!"); // console.log("Table(s) created successfully!");
// ตัวอย่างการทดสอบสร้าง User ทันที (ถ้าต้องการ) // // ตัวอย่างการทดสอบสร้าง User ทันที (ถ้าต้องการ)
const newUser = await User.create({ // const newUser = await User.create({
first_name: "Jane", // first_name: "Jane",
last_name: "Doe", // last_name: "Doe",
email: "jane@example.com", // email: "jane@example.com",
password: "123456", // จะถูก hash จาก hook ใน model // password: "123456", // จะถูก hash จาก hook ใน model
role: "employee", // role: "employee",
}); // });
console.log("New user created:", newUser.user_id); // console.log("New user created:", newUser.user_id);
} catch (error) { // } catch (error) {
console.error("Error creating table(s):", error); // console.error("Error creating table(s):", error);
} finally { // } finally {
// ปิด connection เมื่อเสร็จสิ้นงาน (ขึ้นอยู่กับว่าเราต้องการปิดหรือไม่) // // ปิด connection เมื่อเสร็จสิ้นงาน (ขึ้นอยู่กับว่าเราต้องการปิดหรือไม่)
await sequelize.close(); // await sequelize.close();
} // }
})(); // })();
module.exports = User; module.exports = User;
...@@ -66,23 +66,20 @@ export class LoginPageComponent { ...@@ -66,23 +66,20 @@ export class LoginPageComponent {
body.username = this.email; body.username = this.email;
body.password = this.password; body.password = this.password;
this.authService.login(this.loginForm.controls['username'].value, this.loginForm.controls['password'].value).subscribe(result => { this.authService.login(this.loginForm.controls['username'].value, this.loginForm.controls['password'].value).subscribe(result => {
this.tokenService.saveToken(result.access_token); this.tokenService.saveToken(result.accessToken);
// this.tokenService.saveRefreshToken(result.refreshToken); // this.tokenService.saveRefreshToken(result.refreshToken);
this.tokenService.saveUser(result); this.tokenService.saveUser(result);
if (result.member.status == 1) {
if (result.member.role == 99) { if (result.user.role == 'admin') {
this.router.navigate(['/admin/member-manage']) this.router.navigate(['/admin/home'])
} else {
this.router.navigate(['/admin/member-manage'])
}
} else { } else {
this.error = 'ไม่สามารถใช้งานได้กรุณาติดต่อผู้ให้บริการ' this.router.navigate(['/employee/home'])
} }
// this.routes.navigate(['/admin/member-manage']) // this.routes.navigate(['/admin/member-manage'])
}, (error) => { }, (error) => {
this.disabled = ''; this.disabled = '';
this.error = 'Username หรือ Password ไม่ถูกต้อง'; this.error = 'Username หรือ Password ไม่ถูกต้อง';
this.router.navigate(['/employee/home']) // this.router.navigate(['/employee/home'])
}) })
} }
......
import { TranslateService } from "@ngx-translate/core"; import { TranslateService } from "@ngx-translate/core";
import { BaseModel } from "./base.model"; import { BaseModel } from "./base.model";
import { environment } from "src/environments/environment";
export class UserProfileModel extends BaseModel { export class UserProfileModel extends BaseModel {
memberId: string; user_id: string;
username: string; first_name: string;
password: string; last_name: string;
email: string; email: string;
firstName: string; role: string;
lastName: string;
phoneNumber: string;
role: number;
status: number;
picture: any;
createdAt: string;
updatedAt: string;
constructor( constructor(
data?: Partial<UserProfileModel>, data?: Partial<UserProfileModel>,
translateService?: TranslateService translateService?: TranslateService
) { ) {
super(data, translateService); super(data, translateService);
this.memberId = data?.memberId!; this.user_id = data?.user_id!;
this.username = data?.username! this.first_name = data?.first_name!
this.password = data?.password! this.last_name = data?.last_name!
this.phoneNumber = data?.phoneNumber || ""
this.firstName = data?.firstName || ""
this.lastName = data?.lastName || ""
this.status = data?.status!
this.email = data?.email! this.email = data?.email!
this.role = data?.role! this.role = data?.role!
this.createdAt = data?.createdAt!
this.updatedAt = data?.updatedAt!
}
getRole(): string {
if (this.role == 99) {
return this.translateService.instant('Admin-System')
}
else if (this.role == 1) {
return this.translateService.instant('Admin-Company')
} else {
return this.translateService.instant('User')
}
}
getStatus(): string {
if (this.status == 1) {
return this.translateService.instant('Active')
} else {
return this.translateService.instant('Unactive')
}
}
getPicture(): string {
return this.picture ? environment.baseUrl + '/images/' + this.picture : './assets/images/faces/1.jpg'
}
getFullname(): string {
return this.firstName + " " + this.lastName
} }
} }
...@@ -791,7 +791,7 @@ ...@@ -791,7 +791,7 @@
<i class="ti ti-wallet text-lg"></i> <i class="ti ti-wallet text-lg"></i>
Bal: $7,12,950 Bal: $7,12,950
</a> </a>
<a routerLink="/signin/basic" class="ti-dropdown-item"> <a (click)="logOut()" class="ti-dropdown-item">
<i class="ti ti-logout text-lg"></i> <i class="ti ti-logout text-lg"></i>
Log Out Log Out
</a> </a>
......
/* eslint-disable no-constant-condition */ /* eslint-disable no-constant-condition */
import { Component, ElementRef } from '@angular/core'; import { Component, ElementRef } from '@angular/core';
import { NavService } from '../../services/navservice'; import { NavService } from '../../services/navservice';
import { AuthService } from '../../services/auth.service';
import { TokenService } from '../../services/token.service';
@Component({ @Component({
selector: 'app-header', selector: 'app-header',
...@@ -9,7 +11,7 @@ import { NavService } from '../../services/navservice'; ...@@ -9,7 +11,7 @@ import { NavService } from '../../services/navservice';
}) })
export class HeaderComponent { export class HeaderComponent {
constructor(public navServices: NavService, constructor(public navServices: NavService, private tokenService: TokenService,
private elementRef: ElementRef) { private elementRef: ElementRef) {
} }
...@@ -37,11 +39,11 @@ export class HeaderComponent { ...@@ -37,11 +39,11 @@ export class HeaderComponent {
toggleSidebar() { toggleSidebar() {
let html = this.elementRef.nativeElement.ownerDocument.documentElement; let html = this.elementRef.nativeElement.ownerDocument.documentElement;
if(window.innerWidth <= 992){ if (window.innerWidth <= 992) {
html?.setAttribute('toggled', html?.getAttribute('toggled') == 'open' ? 'close' : 'open'); html?.setAttribute('toggled', html?.getAttribute('toggled') == 'open' ? 'close' : 'open');
if(html?.getAttribute('toggled') == 'open'){ if (html?.getAttribute('toggled') == 'open') {
document.querySelector('#responsive-overlay')?.classList.add('active'); document.querySelector('#responsive-overlay')?.classList.add('active');
}else{ } else {
document.querySelector('#responsive-overlay')?.classList.remove('active'); document.querySelector('#responsive-overlay')?.classList.remove('active');
} }
} }
...@@ -106,4 +108,8 @@ export class HeaderComponent { ...@@ -106,4 +108,8 @@ export class HeaderComponent {
const element: any = document.querySelector('.serachmodal'); const element: any = document.querySelector('.serachmodal');
element.click(); element.click();
} }
logOut() {
this.tokenService.signOut();
}
} }
...@@ -4,6 +4,7 @@ import { Subscription, fromEvent } from 'rxjs'; ...@@ -4,6 +4,7 @@ import { Subscription, fromEvent } from 'rxjs';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { NavigationEnd, Router } from '@angular/router'; import { NavigationEnd, Router } from '@angular/router';
import { checkHoriMenu, switcherArrowFn } from './sidebar'; import { checkHoriMenu, switcherArrowFn } from './sidebar';
import { TokenService } from '../../services/token.service';
@Component({ @Component({
selector: 'app-sidebar', selector: 'app-sidebar',
...@@ -66,17 +67,18 @@ export class SidebarComponent { ...@@ -66,17 +67,18 @@ export class SidebarComponent {
private sanitizer: DomSanitizer, private sanitizer: DomSanitizer,
public router: Router, public router: Router,
public renderer: Renderer2, public renderer: Renderer2,
private elementRef: ElementRef private elementRef: ElementRef,
private tokenService: TokenService,
) { ) {
this.screenWidth = window.innerWidth; this.screenWidth = window.innerWidth;
} }
ngOnInit() { ngOnInit() {
if(true){ if (this.tokenService.getUser().user.role == 'admin') {
this.menuitemsSubscribe$ = this.navServices.itemsAdmin.subscribe((items) => { this.menuitemsSubscribe$ = this.navServices.itemsAdmin.subscribe((items) => {
this.menuItems = items; this.menuItems = items;
}); });
}else{ } else {
this.menuitemsSubscribe$ = this.navServices.itemsEmp.subscribe((items) => { this.menuitemsSubscribe$ = this.navServices.itemsEmp.subscribe((items) => {
this.menuItems = items; this.menuItems = items;
}); });
...@@ -89,7 +91,7 @@ export class SidebarComponent { ...@@ -89,7 +91,7 @@ export class SidebarComponent {
this.ParentActive(); this.ParentActive();
} }
}); });
if(window.innerWidth <= 992){ if (window.innerWidth <= 992) {
document.documentElement?.setAttribute('toggled', 'close'); document.documentElement?.setAttribute('toggled', 'close');
} }
const WindowResize = fromEvent(window, 'resize'); const WindowResize = fromEvent(window, 'resize');
......
...@@ -2,11 +2,12 @@ import { Injectable, NgZone } from '@angular/core'; ...@@ -2,11 +2,12 @@ import { Injectable, NgZone } from '@angular/core';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { ProfileModel, UserModel } from '../user-auth.model'; import { ProfileModel, UserModel } from '../user-auth.model';
import { UserProfileModel } from 'src/app/models/user.model'; import { UserProfileModel } from 'src/app/models/user.model';
import { environment } from 'src/environments/environment';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class AuthService { export class AuthService {
apiBaseUrl = "/auth"; apiBaseUrl = environment.baseUrl + "/auth";
constructor( constructor(
private http: HttpClient, private http: HttpClient,
) { ) {
...@@ -14,7 +15,7 @@ export class AuthService { ...@@ -14,7 +15,7 @@ export class AuthService {
login(username: string, password: string) { login(username: string, password: string) {
const body = { const body = {
username: username, email: username,
password: password, password: password,
}; };
return this.http.post<UserModel>(this.apiBaseUrl + '/login', body) return this.http.post<UserModel>(this.apiBaseUrl + '/login', body)
......
...@@ -31,8 +31,8 @@ export class TokenService { ...@@ -31,8 +31,8 @@ export class TokenService {
window.localStorage.setItem(TOKEN_KEY, token); window.localStorage.setItem(TOKEN_KEY, token);
const user = this.getUser(); const user = this.getUser();
if (user.access_token) { if (user.accessToken) {
this.saveUser({ ...user, access_token: token }); this.saveUser({ ...user, accessToken: token });
} }
} }
......
...@@ -8,9 +8,9 @@ export class LoginModel { ...@@ -8,9 +8,9 @@ export class LoginModel {
export class UserModel { export class UserModel {
public access_token: string = ""; public accessToken: string = "";
public token_type: string = ""; public message: string = "";
public member : UserProfileModel = new UserProfileModel() public user : UserProfileModel = new UserProfileModel()
} }
export interface ProfileModel { export interface ProfileModel {
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
// The list of file replacements can be found in `angular.json`. // The list of file replacements can be found in `angular.json`.
export const environment = { export const environment = {
production: true, production: true,
baseUrl: 'http://localhost:3000', baseUrl: 'http://localhost:3000/api',
firebase: { firebase: {
apiKey: '********************************', apiKey: '********************************',
authDomain: '********************************', authDomain: '********************************',
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment