Skip to content

Commit bbc80bd

Browse files
committed
prepare auth api
1 parent a656fe3 commit bbc80bd

File tree

6 files changed

+135
-9
lines changed

6 files changed

+135
-9
lines changed

app.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ const app = express()
1414

1515
app.use(express.json({ extended: true }))
1616

17-
//app.use('/api/auth', require('./routes/auth.routes'))
18-
app.use('/server', require('./routes/phpserver.routes'))
17+
app.use('/api/auth', require('./routes/auth.routes'))
18+
app.use('/api/server', require('./routes/phpserver.routes'))
1919

2020
if (httpsRedirect) app.use(httpToHttps)
2121

client/src/Services/DataService.js

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ import Card, { checkCardsArr } from '../Cards/cardType/Card'
44
export default function DataService() {
55
////////////////////////////////////////////////////////////
66
var user = null
7-
const nodeBackend = true
8-
const baseUrl = nodeBackend ? '/server/' : 'http://php-server-notes.std-1033.ist.mospolytech.ru/'
7+
const baseUrl = '/api/server/'
98

109
////////////////////////////////////////////////////////////
1110
function updDataServLogin(login) {
@@ -74,7 +73,7 @@ export default function DataService() {
7473
function checkData(data) {
7574
//console.log('start check data')
7675
try {
77-
if( data === null) console.log("null data");
76+
if (data === null) console.log("null data");
7877
return data === null || data === [] || checkCardsArr(data)
7978
} catch {
8079
return false
@@ -93,7 +92,7 @@ export default function DataService() {
9392
.then((d) => {
9493
let data = tryParce(d)//here we parce json
9594
//console.log("[DATA] from loadData(): ", data)
96-
if(!data)console.log("empty data from server");
95+
if (!data) console.log("empty data from server");
9796
if (!checkData(data)) {
9897
console.error("[loadData] Bad data format")
9998
console.log(data)
@@ -121,10 +120,10 @@ export default function DataService() {
121120
? Promise.reject(rej())
122121
: loadData())
123122
.then((d) => {
124-
if(!data)console.log("empty data to post");
125-
if(!d)console.log("empty loaded to check");
123+
if (!data) console.log("empty data to post");
124+
if (!d) console.log("empty loaded to check");
126125
let pDat = data === null ? (d || []) : data
127-
if(!pDat)console.log("empty will be posted");
126+
if (!pDat) console.log("empty will be posted");
128127
requestPostData(pDat).then(res, rej)
129128
})
130129
.catch(rej)

middleware/auth.middleware.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const jwt = require('jsonwebtoken')
2+
require('dotenv').config()
3+
4+
module.exports = (req, res, next) => {
5+
if (req.method === 'OPTIONS') {
6+
return next()
7+
}
8+
9+
try {
10+
11+
const token = req.headers.authorization.split(' ')[1] // "Bearer TOKEN"
12+
13+
if (!token) {
14+
return res.status(401).json({ message: 'Нет авторизации' })
15+
}
16+
17+
const decoded = jwt.verify(token, process.env.jwtSecret)
18+
req.user = decoded
19+
next()
20+
21+
} catch (e) {
22+
res.status(401).json({ message: 'Нет авторизации' })
23+
}
24+
}

models/User.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const {Schema, model, Types} = require('mongoose')
2+
3+
const schema = new Schema({
4+
email: {type: String, required: true, unique: true},
5+
password: {type: String, required: true}
6+
})
7+
8+
module.exports = model('User', schema)

routes/auth.routes.js

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
const {Router} = require('express')
2+
const bcrypt = require('bcryptjs')
3+
require('dotenv').config()
4+
const jwt = require('jsonwebtoken')
5+
const {check, validationResult} = require('express-validator')
6+
const User = require('../models/User')
7+
const router = Router()
8+
9+
// /api/auth/register
10+
router.post(
11+
'/register',
12+
[
13+
check('email', 'Некорректный email').isEmail(),
14+
check('password', 'Минимальная длина пароля 6 символов')
15+
.isLength({ min: 6 })
16+
],
17+
async (req, res) => {
18+
try {
19+
const errors = validationResult(req)
20+
21+
if (!errors.isEmpty()) {
22+
return res.status(400).json({
23+
errors: errors.array(),
24+
message: 'Некорректный данные при регистрации'
25+
})
26+
}
27+
28+
const {email, password} = req.body
29+
30+
const candidate = await User.findOne({ email })
31+
32+
if (candidate) {
33+
return res.status(400).json({ message: 'Такой пользователь уже существует' })
34+
}
35+
36+
const hashedPassword = await bcrypt.hash(password, 12)
37+
const user = new User({ email, password: hashedPassword })
38+
39+
await user.save()
40+
41+
res.status(201).json({ message: 'Пользователь создан' })
42+
43+
} catch (e) {
44+
res.status(500).json({ message: 'Что-то пошло не так, попробуйте снова' })
45+
}
46+
})
47+
48+
// /api/auth/login
49+
router.post(
50+
'/login',
51+
[
52+
check('email', 'Введите корректный email').normalizeEmail().isEmail(),
53+
check('password', 'Введите пароль').exists()
54+
],
55+
async (req, res) => {
56+
try {
57+
const errors = validationResult(req)
58+
59+
if (!errors.isEmpty()) {
60+
return res.status(400).json({
61+
errors: errors.array(),
62+
message: 'Некорректный данные при входе в систему'
63+
})
64+
}
65+
66+
const {email, password} = req.body
67+
68+
const user = await User.findOne({ email })
69+
70+
if (!user) {
71+
return res.status(400).json({ message: 'Пользователь не найден' })
72+
}
73+
74+
const isMatch = await bcrypt.compare(password, user.password)
75+
76+
if (!isMatch) {
77+
return res.status(400).json({ message: 'Неверный пароль, попробуйте снова' })
78+
}
79+
80+
const token = jwt.sign(
81+
{ userId: user.id },
82+
process.env.jwtSecret,
83+
{ expiresIn: '1h' }
84+
)
85+
86+
res.json({ token, userId: user.id })
87+
88+
} catch (e) {
89+
res.status(500).json({ message: 'Что-то пошло не так, попробуйте снова' })
90+
}
91+
})
92+
93+
94+
module.exports = router

routes/phpserver.routes.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const router = Router()
55
//temporary backend url
66
const phpBaseUrl = 'https://php-server-notes.herokuapp.com/'
77

8+
//auth not used
89
router.post('/', /*auth,*/ async (req, res) => {
910
try {
1011
//console.log("backend redirect", req.url)

0 commit comments

Comments
 (0)