|
| 1 | +"use strict"; |
| 2 | +Object.defineProperty(exports, "__esModule", { value: true }); |
| 3 | +exports.getUserContext = void 0; |
| 4 | +const bcrypt_1 = require("bcrypt"); |
| 5 | +const jsonwebtoken_1 = require("jsonwebtoken"); |
| 6 | +let userContext = null; |
| 7 | +class UserContext { |
| 8 | + _users = []; |
| 9 | + constructor() { |
| 10 | + this.createDefaultUser(); |
| 11 | + } |
| 12 | + async login(username, password) { |
| 13 | + const user = this._users.find(user => user.username === username); |
| 14 | + if (!user) { |
| 15 | + return [ |
| 16 | + 404, |
| 17 | + { |
| 18 | + data: null, |
| 19 | + error: 'User does not exist' |
| 20 | + }, |
| 21 | + ]; |
| 22 | + } |
| 23 | + const correctPassword = await (0, bcrypt_1.compare)(password, user.password); |
| 24 | + if (correctPassword) { |
| 25 | + return [ |
| 26 | + 200, |
| 27 | + { |
| 28 | + error: null, |
| 29 | + data: { |
| 30 | + accessToken: (0, jsonwebtoken_1.sign)({ |
| 31 | + username: user.username, |
| 32 | + name: user.name |
| 33 | + }, process.env.JWT_SECRET, { expiresIn: '1h' }) |
| 34 | + } |
| 35 | + } |
| 36 | + ]; |
| 37 | + } |
| 38 | + return [ |
| 39 | + 401, |
| 40 | + { |
| 41 | + error: 'Wrong password. Please try again.', |
| 42 | + data: null |
| 43 | + } |
| 44 | + ]; |
| 45 | + } |
| 46 | + async create(username, password, name = '') { |
| 47 | + const userExist = this._users.some(user => user.username === username); |
| 48 | + if (userExist) { |
| 49 | + return [ |
| 50 | + 409, |
| 51 | + { |
| 52 | + data: null, |
| 53 | + error: 'Username already exists' |
| 54 | + } |
| 55 | + ]; |
| 56 | + } |
| 57 | + if (password.length < 8) { |
| 58 | + return [ |
| 59 | + 400, |
| 60 | + { |
| 61 | + data: null, |
| 62 | + error: 'Password should be more than 8 characters' |
| 63 | + } |
| 64 | + ]; |
| 65 | + } |
| 66 | + const user = { |
| 67 | + username, |
| 68 | + password: await (0, bcrypt_1.hash)(password, 10), |
| 69 | + name |
| 70 | + }; |
| 71 | + this._users.push(user); |
| 72 | + return [ |
| 73 | + 201, |
| 74 | + { |
| 75 | + data: null, |
| 76 | + error: null |
| 77 | + } |
| 78 | + ]; |
| 79 | + } |
| 80 | + async createDefaultUser() { |
| 81 | + const user = { |
| 82 | + username: 'turfadmin', |
| 83 | + password: await (0, bcrypt_1.hash)('turf_password', 10), |
| 84 | + name: 'TurfJS Admin' |
| 85 | + }; |
| 86 | + this._users.push(user); |
| 87 | + } |
| 88 | +} |
| 89 | +function getUserContext() { |
| 90 | + if (!userContext) { |
| 91 | + userContext = new UserContext(); |
| 92 | + } |
| 93 | + return userContext; |
| 94 | +} |
| 95 | +exports.getUserContext = getUserContext; |
0 commit comments