user-authentication

This commit is contained in:
King Wang
2021-06-14 20:57:26 +08:00
parent 54c2f31f83
commit 7b18b2e3b2
38 changed files with 1418 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
node_modules
dist
.DS_STORE

View File

@@ -0,0 +1,30 @@
{
"configurations": [
{
"type": "node",
"request": "launch",
"name": "mocha current file",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"${file}"
],
"internalConsoleOptions": "openOnSessionStart",
"cwd": "${workspaceFolder}"
},
{
"type": "node",
"request": "launch",
"name": "ts-node current file",
"protocol": "inspector",
"args": [
"${relativeFile}"
],
"cwd": "${workspaceRoot}",
"runtimeArgs": [
"-r",
"ts-node/register"
],
"internalConsoleOptions": "openOnSessionStart"
}
]
}

View File

@@ -0,0 +1,3 @@
{
"typescript.tsdk": "node_modules\\typescript\\lib"
}

View File

@@ -0,0 +1,35 @@
# TSRPC Server
## Run
### Local Dev Server
```
npm run dev
```
### Build
```
npm run build
```
---
## Files
### Generate ServiceProto
```
npm run proto
```
### Generate API templates
```
npm run api
```
### Sync shared code to client
```
npm run sync
```
> If you chose symlink when using `create-tsrpc-app`, it would re-create the symlink instead of copy files.

View File

@@ -0,0 +1,25 @@
{
"name": "user-authentication-backend",
"version": "0.1.0",
"main": "index.js",
"private": true,
"scripts": {
"proto": "tsrpc proto -i src/shared/protocols -o src/shared/protocols/serviceProto.ts",
"sync": "tsrpc sync --from src/shared --to ../frontend/src/shared",
"api": "tsrpc api -i src/shared/protocols/serviceProto.ts -o src/api",
"dev": "onchange \"src/**/*.ts\" -i -k -- ts-node \"src/index.ts\"",
"build": "tsrpc build"
},
"devDependencies": {
"@types/node": "^15.12.2",
"@types/uuid": "^8.3.0",
"onchange": "^7.1.0",
"ts-node": "^9.1.1",
"tsrpc-cli": "^2.0.1-dev.12",
"typescript": "^4.3.2"
},
"dependencies": {
"tsrpc": "^3.0.0-dev.20",
"uuid": "^8.3.2"
}
}

View File

@@ -0,0 +1,8 @@
import { ApiCall } from "tsrpc";
import { ReqAdminAction, ResAdminAction } from "../../shared/protocols/action/PtlAdminAction";
export async function ApiAdminAction(call: ApiCall<ReqAdminAction, ResAdminAction>) {
call.succ({
result: 'Success'
})
}

View File

@@ -0,0 +1,8 @@
import { ApiCall } from "tsrpc";
import { ReqGuestAction, ResGuestAction } from "../../shared/protocols/action/PtlGuestAction";
export async function ApiGuestAction(call: ApiCall<ReqGuestAction, ResGuestAction>) {
call.succ({
result: 'Success'
})
}

View File

@@ -0,0 +1,8 @@
import { ApiCall } from "tsrpc";
import { ReqNormalAction, ResNormalAction } from "../../shared/protocols/action/PtlNormalAction";
export async function ApiNormalAction(call: ApiCall<ReqNormalAction, ResNormalAction>) {
call.succ({
result: 'Success'
})
}

View File

@@ -0,0 +1,17 @@
import { ApiCall } from "tsrpc";
import { UserUtil } from "../../models/UserUtil";
import { ReqLogin, ResLogin } from "../../shared/protocols/user/PtlLogin";
export async function ApiLogin(call: ApiCall<ReqLogin, ResLogin>) {
let user = UserUtil.users.find(v => v.username === call.req.username && v.password === call.req.password);
if (!user) {
call.error('Error username or password');
return;
}
let sso = await UserUtil.createSsoToken(user.uid);
call.succ({
__ssoToken: sso
})
}

View File

@@ -0,0 +1,10 @@
import { ApiCall } from "tsrpc";
import { UserUtil } from "../../models/UserUtil";
import { ReqLogout, ResLogout } from "../../shared/protocols/user/PtlLogout";
export async function ApiLogout(call: ApiCall<ReqLogout, ResLogout>) {
call.req.__ssoToken && UserUtil.destroySsoToken(call.req.__ssoToken);
call.succ({
__ssoToken: ''
});
}

View File

@@ -0,0 +1,31 @@
import * as path from "path";
import { HttpServer } from "tsrpc";
import { enableAuthentication } from "./models/enableAuthentication";
import { parseCurrentUser } from "./models/parseCurrentUser";
import { serviceProto } from "./shared/protocols/serviceProto";
// Create the Server
const server = new HttpServer(serviceProto, {
port: 3000,
cors: '*'
});
parseCurrentUser(server);
enableAuthentication(server);
// Entry function
async function main() {
// Auto implement APIs
await server.autoImplementApi(path.resolve(__dirname, 'api'));
// TODO
// Prepare something... (e.g. connect the db)
await server.start();
};
main().catch(e => {
// Exit if any error during the startup
server.logger.error(e);
process.exit(-1);
});

View File

@@ -0,0 +1,5 @@
export interface CurrentUser {
uid: number,
username: string,
roles: string[]
}

View File

@@ -0,0 +1,76 @@
import * as uuid from "uuid";
import { CurrentUser } from "./CurrentUser";
const SSO_VALID_TIME = 86400000 * 7;
export class UserUtil {
// Store data in memory for test
// You can store data into database
static users: {
uid: number,
username: string,
password: string,
roles: string[]
}[] = [
{
uid: 1,
username: 'Normal',
password: '123456',
roles: ['Normal']
},
{
uid: 2,
username: 'Admin',
password: '123456',
roles: ['Admin']
}
];
static ssoTokenInfo: {
[token: string]: { expiredTime: number, uid: number }
} = {};
static async createSsoToken(uid: number): Promise<string> {
let token = uuid.v1();
// Expired after some time without any action
let expiredTime = Date.now() + SSO_VALID_TIME;
this.ssoTokenInfo[token] = {
uid: uid,
expiredTime: expiredTime
};
return token;
}
static async destroySsoToken(ssoToken: string): Promise<void> {
delete this.ssoTokenInfo[ssoToken];
}
static async parseSSO(ssoToken: string): Promise<CurrentUser | undefined> {
let info = this.ssoTokenInfo[ssoToken];
// Token not exists or expired
if (!info || info.expiredTime < Date.now()) {
return undefined;
}
// Parse User
let user = this.users.find(v => v.uid === info.uid);
if (!user) {
return undefined;
}
// Extend expired time
info.expiredTime = Date.now() + SSO_VALID_TIME;
// Return parsed CurrentUser
return {
uid: user.uid,
username: user.username,
roles: user.roles
}
}
}

View File

@@ -0,0 +1,22 @@
import { HttpServer } from "tsrpc";
import { BaseConf } from "../shared/protocols/base";
export function enableAuthentication(server: HttpServer) {
server.flows.preApiCallFlow.push(call => {
let conf: BaseConf | undefined = call.service.conf;
// NeedLogin
if (conf?.needLogin && !call.currentUser) {
call.error('You need login before do this', { code: 'NEED_LOGIN' });
return undefined;
}
// NeedRoles
if (conf?.needRoles?.length && !call.currentUser?.roles.some(v => conf!.needRoles!.indexOf(v) > -1)) {
call.error('You do NOT have authority to do this', { code: 'NO_AUTHORITY' });
return undefined;
}
return call;
})
}

View File

@@ -0,0 +1,21 @@
import { HttpServer } from "tsrpc";
import { BaseRequest } from "../shared/protocols/base";
import { CurrentUser } from "./CurrentUser";
import { UserUtil } from "./UserUtil";
export function parseCurrentUser(server: HttpServer) {
// Auto parse call.currentUser
server.flows.preApiCallFlow.push(async call => {
let req = call.req as BaseRequest;
if (req.__ssoToken) {
call.currentUser = await UserUtil.parseSSO(req.__ssoToken);
}
return call;
})
}
declare module 'tsrpc' {
export interface ApiCall {
currentUser?: CurrentUser;
}
}

View File

@@ -0,0 +1,14 @@
import { BaseRequest, BaseResponse, BaseConf } from '../base'
export interface ReqAdminAction extends BaseRequest {
}
export interface ResAdminAction extends BaseResponse {
result: string
}
export const conf: BaseConf = {
needLogin: true,
needRoles: ['Admin']
};

View File

@@ -0,0 +1,13 @@
import { BaseConf, BaseRequest, BaseResponse } from '../base';
export interface ReqGuestAction extends BaseRequest {
}
export interface ResGuestAction extends BaseResponse {
result: string
}
export const conf: BaseConf = {
needLogin: false
};

View File

@@ -0,0 +1,13 @@
import { BaseConf, BaseRequest, BaseResponse } from '../base';
export interface ReqNormalAction extends BaseRequest {
}
export interface ResNormalAction extends BaseResponse {
result: string
}
export const conf: BaseConf = {
needLogin: true
};

View File

@@ -0,0 +1,13 @@
export interface BaseRequest {
__ssoToken?: string;
}
export interface BaseResponse {
// Init or refresh sso token
__ssoToken?: string;
}
export interface BaseConf {
needLogin?: boolean,
needRoles?: string[]
}

View File

@@ -0,0 +1,279 @@
import { ServiceProto } from 'tsrpc-proto';
import { ReqAdminAction, ResAdminAction } from './action/PtlAdminAction';
import { ReqGuestAction, ResGuestAction } from './action/PtlGuestAction';
import { ReqNormalAction, ResNormalAction } from './action/PtlNormalAction';
import { ReqLogin, ResLogin } from './user/PtlLogin';
import { ReqLogout, ResLogout } from './user/PtlLogout';
export interface ServiceType {
api: {
"action/AdminAction": {
req: ReqAdminAction,
res: ResAdminAction
},
"action/GuestAction": {
req: ReqGuestAction,
res: ResGuestAction
},
"action/NormalAction": {
req: ReqNormalAction,
res: ResNormalAction
},
"user/Login": {
req: ReqLogin,
res: ResLogin
},
"user/Logout": {
req: ReqLogout,
res: ResLogout
}
},
msg: {
}
}
export const serviceProto: ServiceProto<ServiceType> = {
"version": 2,
"services": [
{
"id": 0,
"name": "action/AdminAction",
"type": "api",
"conf": {
"needLogin": true,
"needRoles": [
"Admin"
]
}
},
{
"id": 1,
"name": "action/GuestAction",
"type": "api",
"conf": {
"needLogin": false
}
},
{
"id": 2,
"name": "action/NormalAction",
"type": "api",
"conf": {
"needLogin": true
}
},
{
"id": 3,
"name": "user/Login",
"type": "api",
"conf": {}
},
{
"id": 4,
"name": "user/Logout",
"type": "api",
"conf": {}
}
],
"types": {
"action/PtlAdminAction/ReqAdminAction": {
"type": "Interface",
"extends": [
{
"id": 0,
"type": {
"type": "Reference",
"target": "base/BaseRequest"
}
}
]
},
"base/BaseRequest": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "__ssoToken",
"type": {
"type": "String"
},
"optional": true
}
]
},
"action/PtlAdminAction/ResAdminAction": {
"type": "Interface",
"extends": [
{
"id": 0,
"type": {
"type": "Reference",
"target": "base/BaseResponse"
}
}
],
"properties": [
{
"id": 0,
"name": "result",
"type": {
"type": "String"
}
}
]
},
"base/BaseResponse": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "__ssoToken",
"type": {
"type": "String"
},
"optional": true
}
]
},
"action/PtlGuestAction/ReqGuestAction": {
"type": "Interface",
"extends": [
{
"id": 0,
"type": {
"type": "Reference",
"target": "base/BaseRequest"
}
}
]
},
"action/PtlGuestAction/ResGuestAction": {
"type": "Interface",
"extends": [
{
"id": 0,
"type": {
"type": "Reference",
"target": "base/BaseResponse"
}
}
],
"properties": [
{
"id": 0,
"name": "result",
"type": {
"type": "String"
}
}
]
},
"action/PtlNormalAction/ReqNormalAction": {
"type": "Interface",
"extends": [
{
"id": 0,
"type": {
"type": "Reference",
"target": "base/BaseRequest"
}
}
]
},
"action/PtlNormalAction/ResNormalAction": {
"type": "Interface",
"extends": [
{
"id": 0,
"type": {
"type": "Reference",
"target": "base/BaseResponse"
}
}
],
"properties": [
{
"id": 0,
"name": "result",
"type": {
"type": "String"
}
}
]
},
"user/PtlLogin/ReqLogin": {
"type": "Interface",
"extends": [
{
"id": 0,
"type": {
"type": "Reference",
"target": "base/BaseRequest"
}
}
],
"properties": [
{
"id": 0,
"name": "username",
"type": {
"type": "String"
}
},
{
"id": 1,
"name": "password",
"type": {
"type": "String"
}
}
]
},
"user/PtlLogin/ResLogin": {
"type": "Interface",
"extends": [
{
"id": 0,
"type": {
"type": "Reference",
"target": "base/BaseResponse"
}
}
],
"properties": [
{
"id": 0,
"name": "__ssoToken",
"type": {
"type": "String"
}
}
]
},
"user/PtlLogout/ReqLogout": {
"type": "Interface",
"extends": [
{
"id": 0,
"type": {
"type": "Reference",
"target": "base/BaseRequest"
}
}
]
},
"user/PtlLogout/ResLogout": {
"type": "Interface",
"extends": [
{
"id": 0,
"type": {
"type": "Reference",
"target": "base/BaseResponse"
}
}
]
}
}
};

View File

@@ -0,0 +1,14 @@
import { BaseConf, BaseRequest, BaseResponse } from '../base';
export interface ReqLogin extends BaseRequest {
username: string,
password: string
}
export interface ResLogin extends BaseResponse {
__ssoToken: string;
}
export const conf: BaseConf = {
};

View File

@@ -0,0 +1,13 @@
import { BaseRequest, BaseResponse, BaseConf } from '../base'
export interface ReqLogout extends BaseRequest {
}
export interface ResLogout extends BaseResponse {
}
export const conf: BaseConf = {
};

View File

@@ -0,0 +1,18 @@
{
"compilerOptions": {
"lib": [
"es2018"
],
"module": "commonjs",
"target": "es2018",
"outDir": "dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node"
},
"include": [
"src"
]
}