first commit

This commit is contained in:
Akhil Gupta
2021-05-29 15:20:50 +05:30
commit d25c30a7b2
194 changed files with 49873 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
const fs = require('fs')
const path = require('path')
const bodyParser = require('body-parser')
module.exports = (app) => {
app.use(bodyParser.json())
// Register all routes inside tests/mock-api/routes.
fs.readdirSync(path.join(__dirname, 'routes')).forEach((routeFileName) => {
if (/\.js$/.test(routeFileName)) {
require(`./routes/${routeFileName}`)(app)
}
})
}

View File

@@ -0,0 +1,42 @@
const _ = require('lodash')
module.exports = {
all: [
{
id: 1,
username: 'admin',
password: 'password',
name: 'Vue Master',
},
{
id: 2,
username: 'user1',
password: 'password',
name: 'User One',
},
].map((user) => {
return {
...user,
token: `valid-token-for-${user.username}`,
}
}),
authenticate({ username, password }) {
return new Promise((resolve, reject) => {
const matchedUser = this.all.find(
(user) => user.username === username && user.password === password
)
if (matchedUser) {
resolve(this.json(matchedUser))
} else {
reject(new Error('Invalid user credentials.'))
}
})
},
findBy(propertyName, value) {
const matchedUser = this.all.find((user) => user[propertyName] === value)
return this.json(matchedUser)
},
json(user) {
return user && _.omit(user, ['password'])
},
}

View File

@@ -0,0 +1,33 @@
const Users = require('../resources/users')
module.exports = (app) => {
// Log in a user with a username and password
app.post('/api/session', (request, response) => {
Users.authenticate(request.body)
.then((user) => {
response.json(user)
})
.catch((error) => {
response.status(401).json({ message: error.message })
})
})
// Get the user of a provided token, if valid
app.get('/api/session', (request, response) => {
const currentUser = Users.findBy('token', request.headers.authorization)
if (!currentUser) {
return response.status(401).json({
message:
'The token is either invalid or has expired. Please log in again.',
})
}
response.json(currentUser)
})
// A simple ping for checking online status
app.get('/api/ping', (request, response) => {
response.send('OK')
})
}

View File

@@ -0,0 +1,24 @@
const Users = require('../resources/users')
module.exports = (app) => {
app.get('/api/users/:username', (request, response) => {
const currentUser = Users.findBy('token', request.headers.authorization)
if (!currentUser) {
return response.status(401).json({
message:
'The token is either invalid or has expired. Please log in again.',
})
}
const matchedUser = Users.findBy('username', request.params.username)
if (!matchedUser) {
return response.status(400).json({
message: 'No user with this name was found.',
})
}
response.json(matchedUser)
})
}