-
Notifications
You must be signed in to change notification settings - Fork 1
/
deno-auth-server.ts
91 lines (73 loc) · 2.06 KB
/
deno-auth-server.ts
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
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
import { MongoClient } from "https://deno.land/x/[email protected]/mod.ts";
import * as bcrypt from "https://deno.land/x/bcrypt/mod.ts";
import { v4 } from "https://deno.land/std/uuid/mod.ts";
// Database Connection.
const client = new MongoClient();
client.connectWithUri("mongodb://localhost:27017");
const db = client.database("test");
const users = db.collection("users");
// User Register API
const registerUser = async (
{request,response}:{request:any; response:any }
)=>{
const body = await request.body();
const user = body.value;
let userExist = await users.findOne({email:user.email})
if(userExist){
response.body = {
error:'Email already exist'
}
}else{
const salt:any = v4.generate();
const hashePswd:any = await bcrypt.hash(user.password, salt);
await users.insertOne({
name: user.name,
email: user.email,
password: hashePswd
})
response.body = {message:"Registration Success"};
response.status = 200;
}
}
// User Login API
const loginUser = async (
{request,response}:{request:any; response:any}
) =>{
const body = await request.body();
const user = body.value;
var loggedUser = await users.findOne({email:user.email})
if(!loggedUser){
response.body = {
error:"Email not found"
}
}
var validPswd = await bcrypt.compare(user.password, loggedUser.password)
if(!validPswd){
response.body = {
error:'Invalid Password'
}
}
else{
response.body = {
message:"Login Success"
}
}
}
// Add API for Updating and deletaing a User
// Get All Users
const getAllUsers = async ({response}:{response:any})=>{
let data = await users.find()
response.body = data
}
// Server
const router = new Router()
const app = new Application();
const PORT = 8080;
router
.post("/register", registerUser)
.post("/login", loginUser)
.get("/users", getAllUsers)
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen({ port: PORT });