Commit e12f8281 authored by huanglu's avatar huanglu

feat: 完成资源大部分

parent 1c3f9c81
......@@ -4,20 +4,19 @@ export default class Auth extends Controller {
async login() {
const { ctx } = this
const data = await ctx.service.auth.user.login()
ctx.body = ctx.helper.success(data)
const { token, username } = await ctx.service.auth.user.login()
ctx.res.setHeader('token', token)
ctx.body = ctx.helper.success({ username })
}
async register() {
console.log('====== register')
const { ctx } = this
const data = await ctx.service.auth.user.register()
ctx.body = ctx.helper.success(data, '注册成功')
}
async getUserInfo() {
this.ctx.body = {
ll: 'sfsfs'
}
const { ctx } = this
ctx.body = await ctx.service.auth.user.getUserInfo()
}
}
import { Controller } from "egg";
export default class ResouceController extends Controller {
async getCredential() {
const credential = await this.ctx.service.cos.index.getCredential()
this.ctx.body = this.ctx.helper.success(credential)
}
async createProject() {
const res = await this.ctx.service.project.index.createProject()
this.ctx.body = this.ctx.helper.success(res)
}
async getAllProject() {
const res = await this.ctx.service.project.index.getAllProject()
this.ctx.body = this.ctx.helper.success(res)
}
async updateProject() {
const res = await this.ctx.service.project.index.updateProject()
this.ctx.body = this.ctx.helper.success(res)
}
}
\ No newline at end of file
import utility = require("utility");
export default {
// 处理成功响应
success(res: any, msg = '请求成功') {
......@@ -15,25 +17,27 @@ export default {
msg,
};
},
sendMsg(target: any, msg: {}) {
const { ctx } = this as any;
return {
target,
from: ctx.socket.id,
tm: new Date().getTime(),
msg,
type: 'chat',
};
},
sendGrooupMsg(target: number, msg: {}) {
const { ctx } = this as any;
return {
target,
from: ctx.socket.id,
tm: new Date().getTime(),
msg,
type: 'room',
};
},
// sendMsg(target: any, msg: {}) {
// const { ctx } = this as any;
// return {
// target,
// from: ctx.socket.id,
// tm: new Date().getTime(),
// msg,
// type: 'chat',
// };
// },
// sendGrooupMsg(target: number, msg: {}) {
// const { ctx } = this as any;
// return {
// target,
// from: ctx.socket.id,
// tm: new Date().getTime(),
// msg,
// type: 'room',
// };
// },
md5(value: string) {
return utility.md5(value)
}
};
......@@ -5,9 +5,9 @@ module.exports = () => {
try {
await next();
} catch (err) {
const status = err.status || 500;
const status = err.status || 200;
// 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
const error = status === 500 && err.message || "Internal Server Error";
const error = err.message || err || "Internal Server Error";
// 从 error 对象上读出各个属性,设置到响应中
ctx.status = status
ctx.body = ctx.helper.fail(error)
......
import { Application } from 'egg';
import authRouter from './router/auth';
import router from './router/index';
export default (app: Application) => {
authRouter(app)
router(app)
};
......@@ -2,6 +2,8 @@ import { Application } from "egg";
export default (app: Application) => {
const { controller } = app
app.router.post('/login', controller.auth.login)
app.router.post('/register', controller.auth.register)
const authRouter = app.router.namespace('/user')
authRouter.post('/login', controller.auth.login)
authRouter.post('/register', controller.auth.register)
authRouter.get('/getUserInfo', controller.auth.getUserInfo)
};
\ No newline at end of file
import { Application } from 'egg'
import authRouter from './auth'
import resourceRouter from './resource'
export default (app: Application) => {
authRouter(app)
resourceRouter(app)
}
\ No newline at end of file
import { Application } from "egg";
export default (app: Application) => {
const resourceRouter = app.router.namespace('/resource')
resourceRouter.get('/getCredential', app.controller.resource.getCredential)
resourceRouter.get('/allProject', app.controller.resource.getAllProject)
resourceRouter.post('/createProject', app.controller.resource.createProject)
resourceRouter.post('/updateProject', app.controller.resource.updateProject)
}
\ No newline at end of file
......@@ -8,7 +8,8 @@ export default class AuthService extends Service {
throw new Error('user or password not null ')
}
try {
await (app as any).mysql.insert('user', { username, password })
const pwdMd5 = ctx.helper.md5(password)
await (app as any).mysql.insert('user', { username, password: pwdMd5 })
return {
username
}
......@@ -25,19 +26,37 @@ export default class AuthService extends Service {
}
try {
const result = await (app as any).mysql.get('user', { username })
// const token = this.app.jwt.sign({
// username,
// password
// }, app.config.jwt.secret)
// await (app as any).mysql.update('user', { password, token }, { username })
// return {
// token,
// username
// }
console.log('query user: ', result)
return result
if (!result) {
throw new Error('用户不存在!')
}
const pwdIsOk = ctx.helper.md5(password) === result.password
if (!pwdIsOk) {
throw new Error('密码不存在')
}
const token = this.app.jwt.sign({
username,
password
}, app.config.jwt.secret)
await (app as any).mysql.update('user', { token }, {
where: {
id: result?.id
}
})
return {
token,
username
}
} catch (error) {
throw error
}
}
async getUserInfo() {
const { query } = this.ctx
const { username: user } = query || {}
const { id, username } = await (this.app as any).mysql.get('user', { username: user })
return {
id, username
}
}
}
\ No newline at end of file
import { Service } from "egg";
import * as CosSTS from "qcloud-cos-sts";
export default class CosService extends Service {
async getCredential() {
const { app } = this;
const { cos } = app.config;
const { project } = this.ctx.query || {};
const { SecretId, SecretKey } = cos || {};
if (!project) {
throw new Error("请填写上传项目的名称");
}
const projectIsExit = await (app as any).mysql.get("projects", {
name: project,
});
if (!projectIsExit) {
throw new Error(`不存在 ${project}, 请先创建`);
}
// 配置参数
const config = {
proxy: "",
durationSeconds: 1800,
bucket: "frontend-bkt-1257124244",
region: "ap-chengdu",
allowActions: [
// 简单上传
"name/cos:PutObject",
"name/cos:PostObject",
"name/cos:GetBucket",
"name/cos:GetObject",
// 分片上传
"name/cos:InitiateMultipartUpload",
"name/cos:ListMultipartUploads",
"name/cos:ListParts",
"name/cos:UploadPart",
"name/cos:CompleteMultipartUpload",
],
allowPrefix: "*",
};
// 获取临时密钥
var shortBucketName = config.bucket.substr(
0,
config.bucket.lastIndexOf("-")
);
var appId = config.bucket.substr(1 + config.bucket.lastIndexOf("-"));
var policy = {
version: "2.0",
statement: [
{
action: config.allowActions,
effect: "allow",
principal: { qcs: ["*"] },
resource: [
"qcs::cos:" +
config.region +
":uid/" +
appId +
":prefix//" +
appId +
"/" +
shortBucketName +
"/" +
config.allowPrefix,
],
},
],
};
const credential = await CosSTS.getCredential({
secretId: SecretId,
secretKey: SecretKey,
proxy: config.proxy,
durationSeconds: config.durationSeconds,
policy: policy,
});
return {
...credential,
bucket: config.bucket,
region: config.region,
dir: project,
};
}
}
import { Service } from "egg"
export default class ProjectService extends Service {
async createProject() {
const { ctx } = this
const { project, type, desc } = ctx.request.body
const { mysql } = this.app as any
if (!project) {
throw {
message: `project 字段不存在`
}
}
const isExit = await mysql.get('projects', { name: project })
if (isExit) {
throw {
message: `${project} 已经存在!!`
}
}
await mysql.insert('projects', { name: project, type, desc })
return 'ok'
}
async getAllProject() {
const { mysql } = this.app as any
const { pageSize = 20, pageNo = 0 } = this.ctx.query || {}
const sql = `select id, name project, type, 'desc' from projects limit ?, ?;`
const res = await mysql.query(sql, [pageNo, pageSize])
return res
}
async updateProject() {
const { mysql } = this.app as any
const { type, desc, id } = this.ctx.request.body
await mysql.update('projects', { type, desc }, { id })
return 'ok'
}
}
\ No newline at end of file
......@@ -5,7 +5,7 @@ export default (appInfo: EggAppInfo) => {
config.keys = appInfo.name + "_1607088260928_8707";
config.middleware = ["auth", 'errorHandler'];
config.routerNotAuth = ["/login", "/register"];
config.routerNotAuth = ["/user/login", "/user/register"];
const bizConfig = {
sourceUrl: "https://geek.jkwljy.com/",
......@@ -61,9 +61,14 @@ export default (appInfo: EggAppInfo) => {
user: "root",
password: "root1234",
database: "geek-front",
debug: process.env.NODE_ENV !== 'production'
},
app: true,
agent: false,
},
cos: {
SecretId: 'AKIDJG6HEyXfdP5dw05OhldO2RaV9Xgbe6Wh',
SecretKey: 'Kdg05SKVRb4qMnUv51nRwCHAAuOMULzM'
}
};
};
......@@ -20,6 +20,10 @@ const plugin: EggPlugin = {
mysql:{
enable:true,
package:'egg-mysql',
},
routerPlus: {
enable: true,
package: 'egg-router-plus',
}
};
......
......@@ -26,11 +26,16 @@
"egg": "^2.6.1",
"egg-cors": "^2.2.3",
"egg-jwt": "^3.1.7",
"egg-mysql": "^3.0.0",
"egg-redis": "^2.4.0",
"egg-router-plus": "^1.3.1",
"egg-scripts": "^2.6.0",
"egg-socket.io": "^4.1.6",
"egg-view-nunjucks": "^2.2.0",
"qs": "^6.9.4"
"qcloud-cos-sts": "^3.0.6",
"qs": "^6.9.4",
"tencentcloud-sdk-nodejs": "^4.0.129",
"utility": "^1.17.0"
},
"devDependencies": {
"@types/mocha": "^2.2.40",
......
......@@ -3,11 +3,13 @@
import 'egg';
import ExportAuth from '../../../app/controller/auth';
import ExportResource from '../../../app/controller/resource';
import ExportSocket from '../../../app/controller/socket';
declare module 'egg' {
interface IController {
auth: ExportAuth;
resource: ExportResource;
socket: ExportSocket;
}
}
......@@ -6,12 +6,20 @@ type AnyClass = new (...args: any[]) => any;
type AnyFunc<T = any> = (...args: any[]) => T;
type CanExportFunc = AnyFunc<Promise<any>> | AnyFunc<IterableIterator<any>>;
type AutoInstanceType<T, U = T extends CanExportFunc ? T : T extends AnyFunc ? ReturnType<T> : T> = U extends AnyClass ? InstanceType<U> : U;
import ExportAuthUser from '.../../../app/service/auth/user
import ExportAuthUser from '../../../app/service/auth/user';
import ExportCosIndex from '../../../app/service/cos/index';
import ExportProjectIndex from '../../../app/service/project/index';
declare module 'egg' {
interface IService {
auth: {
user: AutoInstanceType<typeof ExportAuthUser>;
}
cos: {
index: AutoInstanceType<typeof ExportCosIndex>;
}
project: {
index: AutoInstanceType<typeof ExportProjectIndex>;
}
}
}
......@@ -19,6 +19,7 @@ import 'egg-redis';
import 'egg-cors';
import 'egg-jwt';
import 'egg-mysql';
import 'egg-router-plus';
import { EggPluginItem } from 'egg';
declare module 'egg' {
interface EggPlugin {
......@@ -39,5 +40,6 @@ declare module 'egg' {
cors?: EggPluginItem;
jwt?: EggPluginItem;
mysql?: EggPluginItem;
routerPlus?: EggPluginItem;
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment