-
Notifications
You must be signed in to change notification settings - Fork 264
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(xo-server/REST API): implement authentication tokens route
- Loading branch information
Showing
4 changed files
with
110 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
53 changes: 53 additions & 0 deletions
53
packages/xo-server/src/rest-api/middlewares/authentications.mjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
// ----------------------------------------------------------- | ||
|
||
import { invalidCredentials } from 'xo-common/api-errors.js' | ||
|
||
export function authenticateUserFromToken(app) { | ||
return async function (req, res, next) { | ||
const { cookies, ip } = req | ||
const token = cookies.authenticationToken ?? cookies.token | ||
if (token === undefined) { | ||
return next() | ||
} | ||
try { | ||
const { user } = await app.authenticateUser({ token }, { ip }) | ||
return app.runWithApiContext(user, next) | ||
} catch (error) { | ||
if (invalidCredentials.is(error)) { | ||
res.sendStatus(401) | ||
} else { | ||
next(error) | ||
} | ||
} | ||
} | ||
} | ||
|
||
// ----------------------------------------------------------- | ||
|
||
export function isAdmin(app) { | ||
return function (req, res, next) { | ||
const permission = app.apiContext?.permission | ||
|
||
if (permission === undefined || permission !== 'admin') { | ||
res.sendStatus(401) | ||
return | ||
} | ||
|
||
next() | ||
} | ||
} | ||
|
||
// ----------------------------------------------------------- | ||
|
||
export function isUnauthenticated(app) { | ||
return function (req, res, next) { | ||
const user = app.apiContext?.user | ||
|
||
if (user !== undefined) { | ||
res.sendStatus(403) | ||
return | ||
} | ||
|
||
next() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters