-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcredentials.js
More file actions
82 lines (64 loc) · 1.93 KB
/
credentials.js
File metadata and controls
82 lines (64 loc) · 1.93 KB
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
import { getSession } from 'next-auth/react';
import clientPromise from '../../../../lib/mongodb';
import { compare } from 'bcrypt';
import { sign } from 'jsonwebtoken';
export default async function signin(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ message: 'Method not allowed' });
}
const { username, password } = req.body;
if (!username || !password) {
return res
.status(400)
.json({ message: 'Username and password are required' });
}
const client = await clientPromise;
await client.connect();
const db = client.db('ChatGM');
const user = await db.collection('users').findOne({ username });
if (!user) {
return res.status(401).json({ message: 'Invalid username or password' });
}
const passwordsMatch = await compare(password, user.password);
if (!passwordsMatch) {
return res.status(401).json({ message: 'Invalid username or password' });
}
const session = await getSession({ req });
if (session) {
return res.status(400).json({ message: 'You are already signed in' });
}
const sessionData = {
user: {
id: user._id.toString(),
username: user.username
}
};
const newSession = await createSession(sessionData, db);
console.log('THIS is when NextAuth has your session:', newSession);
return res.status(200).json({
message: 'Sign in successful',
session: newSession,
url: 'http://localhost:3000/'
});
}
async function createSession(sessionData, db) {
const session = {
user: {
id: sessionData.user.id,
username: sessionData.user.username
},
createdAt: new Date(),
updatedAt: new Date()
};
const result = await db.collection('sessions').insertOne(session);
const token = sign(
{ id: result.insertedId.toString() },
process.env.JWT_SECRET
);
return {
id: result.insertedId.toString(),
token,
createdAt: session.createdAt,
updatedAt: session.updatedAt
};
}