Skip to content

Commit

Permalink
feat(system-server): impl application & account apis;
Browse files Browse the repository at this point in the history
  • Loading branch information
maslow committed Aug 31, 2021
1 parent 3bbb30f commit c5d6bc0
Show file tree
Hide file tree
Showing 20 changed files with 216 additions and 224 deletions.
4 changes: 2 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@
"$shared": {},
"test": {
"base_url": "http://127.0.0.1:9000",
"sys_admin": "laf-sys",
"sys_password": "laf-sys"
"user": "test",
"passwd": "test"
}
},
"cSpell.words": [
Expand Down
41 changes: 41 additions & 0 deletions packages/system-server/http/account.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@

@token={{login.response.body.$.data.access_token}}

### 注册

POST {{base_url}}/account/signup HTTP/1.1
Content-Type: application/json

{
"username": "{{user}}",
"password": "{{passwd}}"
}


### 登陆
# @name login

POST {{base_url}}/account/login HTTP/1.1
Content-Type: application/json

{
"username": "{{user}}",
"password": "{{passwd}}"
}

### 管理员信息

GET {{base_url}}/account/profile
Authorization: Bearer {{token}}


### 编辑管理员

POST {{base_url}}/account/edit HTTP/1.1
Content-Type: application/json
Authorization: Bearer {{token}}

{
"name": "Maslow",
"avatar": "https://work.zhuo-zhuo.com/file/data/23ttprpxmavkkuf6nttc/PHID-FILE-vzv6dyqo3ev2tmngx7mu/logoL)"
}
30 changes: 30 additions & 0 deletions packages/system-server/http/application.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

@token={{login.response.body.$.data.access_token}}

### Login
# @name login

POST {{base_url}}/account/login HTTP/1.1
Content-Type: application/json

{
"username": "{{user}}",
"password": "{{passwd}}"
}


### Create an application

POST {{base_url}}/apps/create
Content-Type: application/json
Authorization: Bearer {{token}}

{
"name": "test app"
}


### Get my applications

GET {{base_url}}/apps/my
Authorization: Bearer {{token}}
104 changes: 7 additions & 97 deletions packages/system-server/init/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,9 @@
const Config = require('../dist/config').default
const { hashPassword } = require('../dist/lib/utils/hash')
const assert = require('assert')
const { permissions } = require('./sys-permissions')
const { FunctionLoader } = require('./func-loader')
const { Constants } = require('../dist/constants')
const { DatabaseAgent } = require('../dist/lib/db-agent')
const { publishFunctions } = require('../dist/api/function')
const { publishAccessPolicy } = require('../dist/api/rules')
const { publishTriggers } = require('../dist/api/trigger')
const appAdminRules = require('./policies/app-admin.json')
const appUserRules = require('./policies/app-user.json')

Expand All @@ -18,17 +14,8 @@ const sys_accessor = DatabaseAgent.sys_accessor

const db = DatabaseAgent.sys_db

const app_accessor = DatabaseAgent.app_accessor

async function main() {
await sys_accessor.ready
await app_accessor.ready

// init permission
await createInitialPermissions()

// init first role
await createFirstRole()

// create first admin
await createFirstAdmin()
Expand All @@ -39,17 +26,7 @@ async function main() {
// create built-in functions
await createBuiltinFunctions()

// publish policies
await publishAccessPolicy().then(() => console.log('policy deployed'))

// publish functions
await publishFunctions().then(() => console.log('functions deployed'))

// publish triggers
await publishTriggers().then(() => console.log('triggers deployed'))

sys_accessor.close()
app_accessor.close()
}

main()
Expand All @@ -61,24 +38,23 @@ main()
*/
async function createFirstAdmin() {
try {
const username = Config.SYS_ADMIN
const password = hashPassword(Config.SYS_ADMIN_PASSWORD)
const username = Config.SYS_ADMIN || 'root'
const password = hashPassword(Config.SYS_ADMIN_PASSWORD || 'kissme')

const { total } = await db.collection(Constants.cn.admins).count()
const { total } = await db.collection(Constants.cn.accounts).count()
if (total > 0) {
console.log('admin already exists')
return
}

await sys_accessor.db.collection(Constants.cn.admins).createIndex('username', { unique: true })
await sys_accessor.db.collection(Constants.cn.accounts).createIndex('username', { unique: true })

const { data } = await db.collection(Constants.cn.roles).get()
const roles = data.map(it => it.name)
const roles = Object.keys(Constants.roles)

const r_add = await db.collection(Constants.cn.admins).add({
const r_add = await db.collection(Constants.cn.accounts).add({
username,
avatar: "https://static.dingtalk.com/media/lALPDe7szaMXyv3NAr3NApw_668_701.png",
name: 'Admin',
name: 'InitAccount',
roles,
created_at: Date.now(),
updated_at: Date.now()
Expand All @@ -99,72 +75,6 @@ async function createFirstAdmin() {
}
}

/**
* Create the first role
* @returns
*/
async function createFirstRole() {
try {

await sys_accessor.db.collection(Constants.cn.roles).createIndex('name', { unique: true })

const r_perm = await db.collection(Constants.cn.permissions).get()
assert(r_perm.ok, 'get permissions failed')

const permissions = r_perm.data.map(it => it.name)

const r_add = await db.collection(Constants.cn.roles).add({
name: 'superadmin',
label: 'Super Admin',
description: 'init role',
permissions,
created_at: Date.now(),
updated_at: Date.now()
})

assert(r_add.ok, 'add role occurs error')

return r_add.id
} catch (error) {
if (error.code == 11000) {
return console.log('permissions already exists')
}

console.error(error.message)
}
}

/**
* Create initial permissions
* @returns
*/
async function createInitialPermissions() {

// create unique index in permission collection
await sys_accessor.db.collection(Constants.cn.permissions).createIndex('name', { unique: true })

for (const perm of permissions) {
try {
const data = {
...perm,
created_at: Date.now(),
updated_at: Date.now()
}
await db.collection(Constants.cn.permissions).add(data)
console.log('permissions added: ' + perm.name)

} catch (error) {
if (error.code == 11000) {
console.log('permissions already exists: ' + perm.name)
continue
}
console.error(error.message)
}
}

return true
}

/**
* Create initial policies
* @param {string} name policy name
Expand Down
24 changes: 17 additions & 7 deletions packages/system-server/src/api/application.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
/*
* @Author: Maslow<wangfugen@126.com>
* @Date: 2021-08-28 22:00:45
* @LastEditTime: 2021-08-30 17:32:14
* @LastEditTime: 2021-08-31 15:47:43
* @Description: Application APIs
*/

import { Constants } from "../constants"
import { DatabaseAgent } from "../lib/db-agent"
import * as assert from 'assert'
import { MongoAccessor } from "less-api/dist"
import * as crypto from 'crypto'

/**
* The application structure in db
Expand All @@ -25,7 +26,7 @@ export interface ApplicationStruct {
db_max_pool_size: number
server_secret_salt: string
file_system_driver?: string
file_system_enable_unauthorized_upload: string
file_system_enable_unauthorized_upload?: string
file_system_http_cache_control?: string
log_level?: string
enable_cloud_function_log?: string
Expand Down Expand Up @@ -57,16 +58,14 @@ export async function getApplicationById(appid: string) {
/**
* Get application created by account_id
* @param account_id
* @returns
* @returns applications' data array
*/
export async function getMyApplications(account_id: string) {
assert.ok(account_id, 'empty account_id got')

const db = DatabaseAgent.sys_db
const ret = await db.collection(Constants.cn.applications)
.where({
'collaborators.uid': account_id
})
.where({ created_by: account_id })
.get<ApplicationStruct>()

assert.ok(ret.ok, `getMyApplications() got error: ${account_id}`)
Expand All @@ -83,7 +82,9 @@ export async function getMyJoinedApplications(account_id: string) {

const db = DatabaseAgent.sys_db
const ret = await db.collection(Constants.cn.applications)
.where({ created_by: account_id })
.where({
'collaborators.uid': account_id
})
.get<ApplicationStruct>()

assert.ok(ret.ok, `getMyApplications() got error: ${account_id}`)
Expand All @@ -106,4 +107,13 @@ export async function getApplicationDbAccessor(app: ApplicationStruct) {
await accessor.init()

return accessor
}

/**
* Generate application secret string
* @returns
*/
export async function generateApplicationSecret() {
const buf = crypto.randomBytes(64)
return buf.toString('base64')
}
2 changes: 1 addition & 1 deletion packages/system-server/src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @Description:
*/

import { deepFreeze } from "../lib/utils/lang"
import { deepFreeze } from "../utils/lang"
import { permissions } from "./permissions"
import { roles } from "./roles"

Expand Down
2 changes: 1 addition & 1 deletion packages/system-server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import * as express from 'express'
import { parseToken, splitBearerToken } from './lib/utils/token'
import { parseToken, splitBearerToken } from './utils/token'
import { v4 as uuidv4 } from 'uuid'
import Config from './config'
import { router } from './router/index'
Expand Down
29 changes: 4 additions & 25 deletions packages/system-server/src/router/account/edit.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
/*
* @Author: Maslow<wangfugen@126.com>
* @Date: 2021-07-30 10:30:29
* @LastEditTime: 2021-08-28 22:53:24
* @LastEditTime: 2021-08-31 15:35:11
* @Description:
*/

import { Request, Response } from 'express'
import { hashPassword } from '../../lib/utils/hash'
import { DatabaseAgent } from '../../lib/db-agent'
import { Constants } from '../../constants'

Expand All @@ -19,10 +18,9 @@ export async function handleEdit(req: Request, res: Response) {
const db = DatabaseAgent.sys_db

// check if params valid
const { password, avatar, name, roles } = req.body
if (!uid) {
return res.status(401)
}
const { avatar, name } = req.body
if (!uid)
return res.status(401).send()

// check if uid valid
const { data: account } = await db.collection(Constants.cn.accounts)
Expand All @@ -33,25 +31,11 @@ export async function handleEdit(req: Request, res: Response) {
return res.status(422).send('account not found')
}

// check if roles are valid
const { total: valid_count } = await db.collection(Constants.cn.roles)
.where({ name: db.command.in(roles) })
.count()

if (valid_count !== roles.length) {
return res.status(422).send('invalid roles')
}

// update account
const data = {
updated_at: Date.now()
}

// update password if provided
if (password) {
data['password'] = hashPassword(password)
}

// update avatar if provided
if (avatar && avatar != account.avatar) {
data['avatar'] = avatar
Expand All @@ -62,11 +46,6 @@ export async function handleEdit(req: Request, res: Response) {
data['name'] = name
}

// update roles if provided
if (roles) {
data['roles'] = roles
}

const r = await db.collection(Constants.cn.accounts)
.where({ _id: uid })
.update(data)
Expand Down
Loading

0 comments on commit c5d6bc0

Please sign in to comment.