mirror of
https://github.com/HabitRPG/habitica.git
synced 2025-12-19 07:37:25 +01:00
chore(): rename website/src -> website/server and website/public -> website/client (#7199)
This commit is contained in:
75
website/server/middlewares/api-v3/auth.js
Normal file
75
website/server/middlewares/api-v3/auth.js
Normal file
@@ -0,0 +1,75 @@
|
||||
import {
|
||||
NotAuthorized,
|
||||
} from '../../libs/api-v3/errors';
|
||||
import {
|
||||
model as User,
|
||||
} from '../../models/user';
|
||||
|
||||
// Strins won't be translated here because getUserLanguage has not run yet
|
||||
|
||||
// Authenticate a request through the x-api-user and x-api key header
|
||||
// If optional is true, don't error on missing authentication
|
||||
export function authWithHeaders (optional = false) {
|
||||
return function authWithHeadersHandler (req, res, next) {
|
||||
let userId = req.header('x-api-user');
|
||||
let apiToken = req.header('x-api-key');
|
||||
|
||||
if (!userId || !apiToken) {
|
||||
if (optional) return next();
|
||||
return next(new NotAuthorized(res.t('missingAuthHeaders')));
|
||||
}
|
||||
|
||||
return User.findOne({
|
||||
_id: userId,
|
||||
apiToken,
|
||||
})
|
||||
.exec()
|
||||
.then((user) => {
|
||||
if (!user) throw new NotAuthorized(res.t('invalidCredentials'));
|
||||
if (user.auth.blocked) throw new NotAuthorized(res.t('accountSuspended', {userId: user._id}));
|
||||
|
||||
res.locals.user = user;
|
||||
// TODO use either session/cookie or headers, not both
|
||||
req.session.userId = user._id;
|
||||
return next();
|
||||
})
|
||||
.catch(next);
|
||||
};
|
||||
}
|
||||
|
||||
// Authenticate a request through a valid session
|
||||
export function authWithSession (req, res, next) {
|
||||
let userId = req.session.userId;
|
||||
|
||||
if (!userId) return next(new NotAuthorized(res.t('invalidCredentials')));
|
||||
|
||||
return User.findOne({
|
||||
_id: userId,
|
||||
})
|
||||
.exec()
|
||||
.then((user) => {
|
||||
if (!user) throw new NotAuthorized(res.t('invalidCredentials'));
|
||||
|
||||
res.locals.user = user;
|
||||
return next();
|
||||
})
|
||||
.catch(next);
|
||||
}
|
||||
|
||||
export function authWithUrl (req, res, next) {
|
||||
let userId = req.query._id;
|
||||
let apiToken = req.query.apiToken;
|
||||
|
||||
if (!userId || !apiToken) {
|
||||
throw new NotAuthorized(res.t('missingAuthParams'));
|
||||
}
|
||||
|
||||
return User.findOne({ _id: userId, apiToken }).exec()
|
||||
.then((user) => {
|
||||
if (!user) throw new NotAuthorized(res.t('invalidCredentials'));
|
||||
|
||||
res.locals.user = user;
|
||||
return next();
|
||||
})
|
||||
.catch(next);
|
||||
}
|
||||
Reference in New Issue
Block a user