123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- import { HttpMethod, Route, StatusCodes } from 'org.crazydoctor.expressts';
- import { Request, Response } from 'express';
- import { ISession } from '../session/ISession';
- import SHA256 from '../util/SHA256';
- import ServerApp from '..';
- class PostAuthorize extends Route {
- private AdminLogin = 'Admin';
- private async tryGogsAuth(login: string, password: string): Promise<boolean> {
- try {
- const response = await fetch(`${ServerApp.GitHost}/api/v1/users/${login}/tokens`, {
- method: 'GET',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': 'Basic ' + Buffer.from(`${login}:${password}`).toString('base64')
- }
- });
- if (!response.ok)
- return false;
- const tokens = await response.json();
-
- if(tokens instanceof Array)
- return true;
- return false;
- } catch (error) {
- return false;
- }
- }
- protected action = (req: Request, res: Response): any => {
- const session = req.session as ISession;
- const params = req.body;
- const login = params.login.trim();
- const password = params.password.trim();
- const hashedPassword = SHA256.hash(password);
- const returnTo = session.returnTo;
- delete session.returnTo;
- res.set({
- 'Content-Type': 'application/json'
- });
- if(login === this.AdminLogin && this.context.options.adminPassword === hashedPassword) {
- session.login = 'Admin';
- session.isAdmin = session.isEditor = true;
- res.status(StatusCodes.OK).send({ success: true, returnTo: returnTo });
- return;
- }
- this.tryGogsAuth(login, password).then((result) => {
- if(result) {
- session.isEditor = true;
- session.login = login;
- res.status(StatusCodes.OK).send({ success: true, returnTo: returnTo });
- } else {
- res.status(StatusCodes.FORBIDDEN).send({ success: false, message: 'Authentication failed' });
- }
- });
- };
- protected method = HttpMethod.POST;
- protected order = 2;
- protected route = '/authorize';
- }
- export default PostAuthorize;
|