auth-system.js

2.16 KB
05/11/2024 05:55
JS
auth-system.js
export class AuthSystem {
    constructor() {
        this.storageKey = 'authData';
        this.sessionDuration = 3600000; // 1 hour
        this.loadAuth();
    }

    loadAuth() {
        const savedAuth = localStorage.getItem(this.storageKey);
        if (savedAuth) {
            const auth = JSON.parse(savedAuth);
            if (Date.now() - auth.timestamp < this.sessionDuration) {
                this.currentUser = auth.user;
                return;
            }
            localStorage.removeItem(this.storageKey);
        }
        this.currentUser = null;
    }

    async login(username, password) {
        try {
            // ในที่นี้ควรใช้ API จริงสำหรับการตรวจสอบ
            const hashedPassword = await this.hashPassword(password);
            if (this.validateCredentials(username, hashedPassword)) {
                this.currentUser = {
                    username,
                    role: 'admin',
                    timestamp: Date.now()
                };
                localStorage.setItem(this.storageKey, JSON.stringify(this.currentUser));
                return true;
            }
            return false;
        } catch (error) {
            console.error('Login failed:', error);
            return false;
        }
    }

    logout() {
        this.currentUser = null;
        localStorage.removeItem(this.storageKey);
    }

    isAuthenticated() {
        return !!this.currentUser;
    }

    hasRole(role) {
        return this.currentUser?.role === role;
    }

    async hashPassword(password) {
        const encoder = new TextEncoder();
        const data = encoder.encode(password);
        const hash = await crypto.subtle.digest('SHA-256', data);
        return Array.from(new Uint8Array(hash))
            .map(b => b.toString(16).padStart(2, '0'))
            .join('');
    }

    // ตรวจสอบ credentials (ในที่นี้เป็นตัวอย่าง)
    validateCredentials(username, hashedPassword) {
        // ควรใช้ระบบ authentication จริง
        return username === 'admin' && hashedPassword.length === 64;
    }
}