| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249 |
- const userModel = require('../model/user')
- const jwt = require('jsonwebtoken')
- const bcrypt = require('bcrypt')
- const secret = require('../config/secret')
- const Response = require('../util/response')
- const aliClient = require('../util/aliClient')
- const getTokenUser = require('../util/tokenProcessor')
- class UserController {
- /**
- * 登录
- * @param ctx
- * @returns {Promise.<void>}
- */
- static async login (ctx) {
- const data = ctx.request.body
- const user = await userModel.findByPhone(data.phone)
- if (user) {
- const confirmRes = bcrypt.compareSync(data.password, user.password)
- if (!confirmRes) {
- ctx.body = Response.failed('密码错误,请重试')
- } else if (!user.isValid) {
- ctx.body = Response.failed('账号封禁中')
- } else {
- // console.log('ctx',ctx);
- // console.log('ctx.cookies.redirect_uri',ctx.cookies.get('redirect_uri'));
- let redirectUri = ctx.cookies.get('redirect_uri')
- let clientId = ctx.cookies.get('client_id')
- if (!redirectUri) {
- redirectUri = ctx.origin + '/api/receiveIDToken'
- }
- if (!clientId) {
- clientId = 'seec-portal'
- }
- const data = {
- iss: 'p.seecoder.cn',
- sub: user.phone,
- aud: clientId,
- auth_time: Math.floor(new Date().getTime() / 1000),
- iat: Math.floor(new Date().getTime() / 1000),
- exp: Math.floor(new Date().getTime() / 1000 + 24 * 60 * 60),
- user_info: { phone: user.phone, email: user.email, id: user.id, name: user.name, role: user.role }
- }
- const token = jwt.sign(data, secret.sign)
- // ctx.redirect(redirect_uri + "?id_token=" + token);
- ctx.cookies.set('redirect_uri', '', {
- maxAge: 0
- })
- ctx.cookies.set('client_id', '', {
- maxAge: 0
- })
- ctx.body = Response.success({ token: token, name: user.name, path: redirectUri })
- }
- } else {
- ctx.body = Response.failed('此账号不存在')
- }
- }
- /**
- * 注册
- * @param ctx
- * @returns {Promise.<void>}
- */
- static async register (ctx) {
- const myReg = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/
- const myReg2 = /^\w+$/
- const data = ctx.request.body
- if (!ctx.session.verification_phone || !ctx.session.verification_code) {
- ctx.body = Response.failed('请重新获取验证码')
- } else if (ctx.session.verification_code !== data.identifyCode || ctx.session.verification_phone !== data.phone) {
- ctx.body = Response.failed('验证码错误')
- } else if (!myReg.test(data.email)) {
- ctx.body = Response.failed('邮箱格式有误')
- } else if (data.name.length < 1 || data.name.length > 10 || data.password.length < 6 || data.password.length > 20 || data.phone.length !== 11 || !myReg2.test(data.name)) {
- ctx.body = Response.failed('参数非法')
- } else {
- const hashPassword = bcrypt.hashSync(data.password, 10)
- const result = await userModel.create(data.name, hashPassword, data.phone, data.email)
- ctx.session.verification_phone = undefined
- ctx.session.verification_code = undefined
- if (result.code === 0) {
- ctx.body = Response.success({ name: result.data.name })
- } else if (result.code === -2) {
- ctx.body = Response.failed('此手机号已注册')
- } else if (result.code === -1) {
- ctx.body = Response.failed('此用户名已使用')
- }
- }
- }
- static async sendMessage (ctx) {
- const { phone } = ctx.request.body
- let code = ''
- for (let i = 0; i < 6; i++) {
- code += Math.floor(Math.random() * 10)
- }
- const params = {
- PhoneNumbers: phone,
- SignName: 'seeccoder',
- TemplateCode: 'SMS_181555598',
- TemplateParam: '{"code":"' + code + '"}'
- }
- // TODO: ??? 这里写个 options 到底是要干啥
- // const options = {
- // timeout: 3000, // default 3000 ms
- // formatAction: true, // default true, format the action to Action
- // formatParams: true, // default true, format the parameter name to first letter upper case
- // method: 'GET', // set the http method, default is GET
- // headers: {} // set the http request headers
- // }
- try {
- const result = await aliClient.request('SendSms', params)
- // console.log("result:", result);
- if (result.Code === 'OK') {
- ctx.session.maxAge = 5 * 60 * 1000
- ctx.session.verification_code = code
- ctx.session.verification_phone = phone
- // console.log('verification_code:', ctx.session.verification_code);
- ctx.body = Response.success({ message: '发送成功' })
- } else {
- console.log('error:', result.message)
- ctx.body = Response.failed('发送失败,请重试')
- }
- } catch (e) {
- console.log(e)
- ctx.body = Response.failed('发送失败,请重试')
- }
- }
- static async getInfo (ctx) {
- const theUser = getTokenUser(ctx)
- if (!theUser) {
- ctx.status = 401
- } else {
- const id = theUser.id
- const user = await userModel.findByUid(id)
- if (user) {
- ctx.body = Response.success({ phone: user.phone, email: user.email, id: user.id, name: user.name, signature: user.signature })
- } else {
- ctx.body = Response.failed('用户信息获取失败')
- }
- }
- }
- static async saveName (ctx) {
- const theUser = getTokenUser(ctx)
- if (!theUser) {
- ctx.status = 401
- } else {
- const id = theUser.id
- const newName = ctx.request.body.newName
- const result = await userModel.updateName(id, newName)
- if (result.code === 0) {
- ctx.body = Response.success({})
- } else {
- ctx.body = Response.failed('此昵称已被占用')
- }
- }
- }
- static async saveEmail (ctx) {
- const theUser = await getTokenUser(ctx)
- if (!theUser) {
- ctx.status = 401
- } else {
- const id = theUser.id
- const newEmail = ctx.request.body.newEmail
- const myReg = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/
- if (!myReg.test(newEmail)) {
- ctx.body = Response.failed('邮箱格式有误')
- } else {
- const result = await userModel.updateEmail(id, newEmail)
- if (result.code === 0) {
- ctx.body = Response.success({})
- } else {
- ctx.body = Response.failed('修改失败')
- }
- }
- }
- }
- static async saveSignature (ctx) {
- const theUser = await getTokenUser(ctx)
- if (!theUser) {
- ctx.status = 401
- } else {
- const id = theUser.id
- const newSignature = ctx.request.body.newSignature
- if (newSignature === 0) {
- ctx.body = Response.failed('个性签名不得为空')
- } else if (newSignature > 20) {
- ctx.body = Response.failed('个性签名过长')
- } else {
- const result = await userModel.updateSignature(id, newSignature)
- if (result.code === 0) {
- ctx.body = Response.success({})
- } else {
- ctx.body = Response.failed('修改失败')
- }
- }
- }
- }
- static async resetPassword (ctx) {
- const data = ctx.request.body
- if (!ctx.session.verification_phone || !ctx.session.verification_code) {
- ctx.body = Response.failed('请重新获取验证码')
- } else if (ctx.session.verification_code !== data.identifyCode || ctx.session.verification_phone !== data.phone) {
- ctx.body = Response.failed('验证码错误')
- } else if (data.password.length < 6 || data.password.length > 20 || data.phone.length !== 11) {
- ctx.body = Response.failed('参数非法')
- } else {
- const hashPassword = bcrypt.hashSync(data.password, 10)
- const result = await userModel.resetPassword(data.phone, hashPassword)
- ctx.session.verification_phone = undefined
- ctx.session.verification_code = undefined
- if (result) {
- ctx.body = Response.success({})
- } else {
- ctx.body = Response.failed('此手机号未注册')
- }
- }
- }
- /**
- * 手机号搜id
- */
- static async findIdByPhone (ctx) {
- const phone = ctx.params.phone
- const user = await userModel.findByPhone(phone)
- if (user) {
- ctx.body = Response.success({ id: user.id })
- } else {
- ctx.body = Response.failed('此手机号未注册')
- }
- }
- }
- module.exports = UserController
|