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 @@
.DS_STORE
node_modules
dist

View File

@@ -0,0 +1,21 @@
{
"name": "user-authentication-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "webpack serve --mode=development --open",
"build": "webpack --mode=production"
},
"devDependencies": {
"copy-webpack-plugin": "^9.0.0",
"html-webpack-plugin": "^5.3.1",
"ts-loader": "^9.2.3",
"typescript": "^4.3.2",
"webpack": "^5.38.1",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"tsrpc-browser": "^3.0.0-dev.16"
}
}

View File

@@ -0,0 +1,99 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
padding: 20px;
}
h1,
h2 {
text-align: center;
margin-bottom: 20px;
}
.status {
width: 1000px;
margin: 20px auto;
text-align: center;
background: #f2f2f2;
padding: 20px;
}
.status.logined {
background: #2c81b9;
color: #fff;
}
.row {
display: flex;
background-color: #f2f2f2;
padding: 20px;
margin: 20px auto 0 auto;
width: 1000px;
}
.row>* {
flex: 1;
margin-right: 20px;
padding: 20px;
background: #d9d9d9;
}
.row>*:last-child {
margin-right: 0;
}
label {
display: inline-block;
width: 40%;
line-height: 1.5rem;
}
input {
display: inline-block;
width: 60%;
padding: 10px;
font-size: 1rem;
}
p {
margin-bottom: 10px;
}
button {
font-size: 20px;
padding: 10px 20px;
cursor: pointer;
display: block;
margin: 10px auto;
}
.action>div {
text-align: center;
}
.action .hint {
font-size: 14px;
color: #999;
}
.action h3 {
margin-bottom: 10px;
}
pre {
background: #333;
border-radius: 5px;
padding: 10px;
color: #fff;
min-height: 80px;
text-align: left;
white-space: pre-wrap;
}
.return {
display: none;
}

View File

@@ -0,0 +1,68 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TSRPC Example</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<h1>Login and Role Authentication</h1>
<div class="status">Not Logined</div>
<div class="row user">
<div class="login-normal">
<h2>Normal</h2>
<p><button>Login as Normal Role</button></p>
</div>
<div class="login-admin">
<h2>Admin</h2>
<p><button>Login as Admin Role</button></p>
</div>
<div class="logout">
<h2>Logout</h2>
<p><button>Logout</button></p>
</div>
</div>
<div class="row action">
<div class="normal">
<h2>Normal Action</h2>
<p class="hint">Need login</p>
<p><button>Do This</button></p>
<div class="return">
<h3>Return</h3>
<pre></pre>
</div>
</div>
<div class="admin">
<h2>Admin Action</h2>
<p class="hint">Need Admin role</p>
<p><button>Do This</button></p>
<div class="return">
<h3>Return</h3>
<pre></pre>
</div>
</div>
<div class="guest">
<h2>Guest Action</h2>
<p class="hint">Do NOT need login</p>
<p><button>Do This</button></p>
<div class="return">
<h3>Return</h3>
<pre></pre>
</div>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,108 @@
import { HttpClient } from 'tsrpc-browser';
import { BaseResponse } from './shared/protocols/base';
import { serviceProto } from './shared/protocols/serviceProto';
const $ = document.querySelector.bind(document) as (v: string) => HTMLElement;
// Create Client
let client = new HttpClient(serviceProto, {
server: 'http://127.0.0.1:3000',
logger: console
});
// Flow
client.flows.postApiReturnFlow.push(v => {
if (v.return.isSucc) {
let res = v.return.res as BaseResponse;
if (res.__ssoToken !== undefined) {
localStorage.setItem('SSO_TOKEN', res.__ssoToken);
}
}
else if (v.return.err.code === 'NEED_LOGIN') {
localStorage.removeItem('SSO_TOKEN');
setStatus(false);
}
return v;
});
client.flows.preCallApiFlow.push(v => {
let ssoToken = localStorage.getItem('SSO_TOKEN');
if (ssoToken) {
v.req.__ssoToken = ssoToken;
}
return v;
})
// User
$('.login-normal button').onclick = async () => {
let ret = await client.callApi('user/Login', {
username: 'Normal',
password: '123456'
});
if (!ret.isSucc) {
alert(ret.err.message);
return;
}
localStorage.setItem('LoginedRole', 'Normal');
setStatus(true);
document.querySelectorAll<HTMLElement>('.return').forEach(v => { v.style.display = 'none' });
}
$('.login-admin button').onclick = async () => {
let ret = await client.callApi('user/Login', {
username: 'Admin',
password: '123456'
});
if (!ret.isSucc) {
alert(ret.err.message);
return;
}
localStorage.setItem('LoginedRole', 'Admin');
setStatus(true);
document.querySelectorAll<HTMLElement>('.return').forEach(v => { v.style.display = 'none' });
}
$('.logout button').onclick = async () => {
let ret = await client.callApi('user/Logout', {});
if (!ret.isSucc) {
alert(ret.err.message);
return;
}
setStatus(false);
document.querySelectorAll<HTMLElement>('.return').forEach(v => { v.style.display = 'none' });
}
// Actions
$('.action .guest button').onclick = async () => {
let ret = await client.callApi('action/GuestAction', {});
$('.action .guest pre').innerText = JSON.stringify(ret, null, 2);
$('.action .guest pre').style.background = ret.isSucc ? 'green' : 'darkred';
$('.action .guest .return').style.display = 'block';
}
$('.action .normal button').onclick = async () => {
let ret = await client.callApi('action/NormalAction', {});
$('.action .normal pre').innerText = JSON.stringify(ret, null, 2);
$('.action .normal pre').style.background = ret.isSucc ? 'green' : 'darkred';
$('.action .normal .return').style.display = 'block';
}
$('.action .admin button').onclick = async () => {
let ret = await client.callApi('action/AdminAction', {});
$('.action .admin pre').innerText = JSON.stringify(ret, null, 2);
$('.action .admin pre').style.background = ret.isSucc ? 'green' : 'darkred';
$('.action .admin .return').style.display = 'block';
}
function setStatus(logined: boolean) {
if (logined) {
$('.status').className = 'status logined';
$('.status').innerText = `Logined as ${localStorage.getItem('LoginedRole')} Role`;
}
else {
$('.status').className = 'status';
$('.status').innerText = 'Not Logined';
}
}
setStatus(!!localStorage.getItem('SSO_TOKEN'));

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,23 @@
{
"compilerOptions": {
"lib": [
"dom",
"es2018"
],
"module": "esnext",
"target": "es2018",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"outDir": "dist",
"skipLibCheck": true,
"strict": true,
"jsx": "react-jsx",
"sourceMap": true,
"isolatedModules": true
},
"include": [
"src"
]
}

View File

@@ -0,0 +1,58 @@
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const isProduction = process.argv.indexOf('--mode=production') > -1;
module.exports = {
entry: './src/index.ts',
output: {
filename: 'bundle.[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true
},
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
module: {
rules: [
{
test: /\.tsx?$/,
use: [{
loader: 'ts-loader',
options: {
compilerOptions: isProduction ? {
"lib": [
"dom",
"es2015.promise"
],
"target": "es5",
} : undefined
}
}],
exclude: /node_modules/
},
]
},
plugins: [
// Copy "public" to "dist"
new CopyWebpackPlugin({
patterns: [{
from: 'public',
to: '.',
toType: 'dir',
globOptions: {
gitignore: true,
ignore: [path.resolve(__dirname, 'public/index.html').replace(/\\/g, '/')]
},
noErrorOnMissing: true
}]
}),
// Auto add <script> to "index.html"
new HtmlWebpackPlugin({
template: 'public/index.html'
}),
],
devtool: isProduction ? false : 'inline-source-map'
}