-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathauth.js
128 lines (113 loc) · 4.68 KB
/
auth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
const bcrypt = require('bcryptjs');
const helper = require('../helper')
const Router = require('express-promise-router')
const db = require('../db')
var fs = require('fs') // for handling data files such as photos
var path = require('path'); //
// create a new express-promise-router
// this has the same API as the normal express router except
// it allows you to use async functions as route handlers
const router = new Router()
// export our router to be mounted by the parent application
module.exports = router
router.post('/signup', async (req,res) => {
var r = {'success':true}
const {
name,
username,
password
} = req.body
// checking whether the username exists
const { rows } = await db.query('SELECT name FROM users WHERE username = $1',[username])
if(rows < 1){
// the username is free
var pwdsalt = bcrypt.genSaltSync(10)
var hashedpass = bcrypt.hashSync(password, pwdsalt)
const accessToken = helper.generateToken(20)
try{
const { rows } = await db.query('INSERT INTO users (name, username, password, access_token) VALUES ($1, $2, $3, $4) RETURNING *', [name, username, hashedpass, accessToken])
// if there is one row the user was created
if(rows.length > 0){
// go ahead and send the user their data
const userID = rows[0]["id"]
// copy the default profile photo and set it as this users photo in data/profile_photos
// this is not a good system of handling profile photos
fs.createReadStream(path.resolve(__dirname + "/../data/profile_photos/default_photo.jpg")).pipe(fs.createWriteStream(path.resolve(__dirname + "/../data/profile_photos/" + userID + ".jpg")))
var userdata = rows[0]
delete(userdata['password']) // removing password from userdata
r.userdata = userdata
res.status(200).json(r)
}
}catch(error){
console.log(error)
req.status(500).send("Not looking too good. Couldn't create your account")
}
}else{
// username is already in use
r.success = false
r.message = "That username is taken"
res.status(200).json(r)
}
})
router.post('/login', async (req,res) => {
var r = {'success':true}
const {
username,
password
} = req.body
async function updateAccessToken(token,username){
try{
const { rowCount } = await db.query('UPDATE users SET access_token = $1 WHERE username = $2 RETURNING ID;', [token,username])
console.log(rowCount)
if (rowCount> 0) return true
}catch(error){
console.log(error)
return false
}
}
db.query('SELECT * FROM users WHERE username = $1', [username], (error, results) => {
if (error || results.rows == 0) {
r.success = false
if(results.rows == 0) r.message = "That user doesn't exist."
else r.message = "Something went wrong back here. Can you try again?"
res.status(200).json(r) // these responses can be handled quite better than this
}else{
// the user does exist
// check their password authenticity
if(bcrypt.compareSync(password, results.rows[0]['password'])){
// the user can login
// generate an access token, update it the users table entry and send it to them
const accessToken = helper.generateToken(20)
// updating the access token
if(updateAccessToken(accessToken,username)){
// we're good
var userdata = results.rows[0]
userdata['access_token'] = accessToken // updating the token
delete(userdata['password']) // removing password from userdata
r.userdata = results.rows[0]
res.status(200).json(r)
}else{
// something went wrong
r.success = false;
r.message = "Something went wrong. Try again maybe?"
res.status(500).json(r)
}
}else{
// password is incorrect
r.success = false;
r.message = "Password is incorrect."
res.status(200).json(r)
}
}
})
})
router.get('/test', async (req,res) => {
try{
const { rows } = await db.query('SELECT * FROM users')
console.log(rows)
res.status(200).json(rows)
}catch(error){
console.log(error)
res.status(500).send("Hmmm...")
}
})