Skip to content

Commit

Permalink
yyh
Browse files Browse the repository at this point in the history
  • Loading branch information
Cbinbin committed Apr 14, 2017
1 parent 8f87730 commit ad884d3
Show file tree
Hide file tree
Showing 18 changed files with 424 additions and 0 deletions.
41 changes: 41 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules
jspm_packages

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

# Important Information
.env
.DS_Store
20 changes: 20 additions & 0 deletions models/Apply.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const mongoose = require('mongoose')
, Schema = mongoose.Schema
, User = require('./User')

const applySchema = new Schema({
selfId: {
type: Schema.Types.ObjectId,
ref: 'User'
},
toUser: {
type: Schema.Types.ObjectId,
ref: 'User'
},
affix: { type: String }, //留言
applyCreated: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('Apply', applySchema)
20 changes: 20 additions & 0 deletions models/Cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const mongoose = require('mongoose')
, Schema = mongoose.Schema
, User = require('./User')
, Apply = require('./Apply')

const cacheSchema = new Schema({
userId: {
type: Schema.Types.ObjectId,
ref: 'User'
},
applyId: [{
type: Schema.Types.ObjectId,
ref: 'Apply'
}],
cacheCreated: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('Cache', cacheSchema)
18 changes: 18 additions & 0 deletions models/Cert.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const mongoose = require('mongoose')
, Schema = mongoose.Schema
, User = require('./User')

const certSchema = new Schema({
userId: {
type: Schema.Types.ObjectId,
ref: 'User'
},
realName: { type: String }, //真实姓名
ID_No: { type: Number }, //身份证号
ID_Pic: { type: String }, //身份证图片
certCreated: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('Cert', certSchema)
59 changes: 59 additions & 0 deletions models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const mongoose = require('mongoose')
, Schema = mongoose.Schema
, Cert = require('./Cert')

const userSchema = new Schema({
//微信信息
openId: {
type: String,
required: true
},
weixiName: { type: String },
headimg: { type: String },
sex: { type: String },
province: { type: String },
city: { type: String },
//完善信息
phone: { type: Number },
weixin: { type: String }, //微信号
dateBirth: { type: String }, //出生日期 [计算年龄]
unit: { type: String }, //单位
education: { type: String }, //学历
specialty: { type: String }, //特长
hobby: { type: String }, //爱好
height: { type: Number }, //身高
weight: { type: Number }, //体重
bloodType: { type: String }, //血型
constellation: { type: String }, //星座
currentLocation: { type: String }, //当前位置
jobType: { type: String }, //工作类型
motto: { type: String }, //格言
photos: [{ type: String }], //相册
beLikes: { type: Number }, //被赞数
adoptedIds: [{ //可看信息的人
type: Schema.Types.ObjectId,
ref: 'User'
}],

// ulat: { type: Number }, //纬度
// ulng: { type: Number }, //经度
certification: { type: Boolean },
certId: {
type: Schema.Types.ObjectId,
ref: 'Cert'
},
userCreated: {
type: Date,
default: Date.now
},
userUpdated: {
type: Date,
default: Date.now
}
}, {
timestamps: {
createdAt: 'userCreated',
updatedAt: 'userUpdated'
}
})
module.exports = mongoose.model('User', userSchema)
8 changes: 8 additions & 0 deletions mongodb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const mongoose = require('mongoose')
, db = mongoose.connection

mongoose.connect('mongodb://localhost/youyuan')
db.on('error', console.error.bind(console, 'connect error:'))
db.once('open', ()=> {
console.log('mongoose opened!')
})
23 changes: 23 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "yyh_api",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "mocha"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.16.0",
"cors": "^2.8.1",
"crypto": "0.0.3",
"dotenv": "^4.0.0",
"express": "^4.15.2",
"jsonwebtoken": "^7.2.1",
"jssha": "^2.2.0",
"mongoose": "^4.8.1",
"superagent": "^3.4.1",
"ws": "^2.2.3"
}
}
58 changes: 58 additions & 0 deletions routes/functions/wechat/setInfo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const jwt = require('jsonwebtoken')
, User = require('../../../models/User')
, youyuanSalt = process.env.YY_SALTKEY

function setInfo(wxInfo, res) {
User.findOne({openId: wxInfo.openId})
.exec((err, same)=> {
if(err) return res.send({code: 500, errMsg: err, data: [] })
if(same) {
jwt.sign({userId: same._id, opId: same.openId},
youyuanSalt,
{expiresIn: '10d'},
(err, token)=> {
if(err) return res.send({code: 500, errMsg: err, data: [] })
res.send({code: 201, errMsg: 'ok', data: {token: token} })
})
} else {
const info = new User({
openId: wxInfo.openId,
weixiName: wxInfo.nickName,
headimg: wxInfo.avatarUrl,
sex: wxInfo.sex,
province: wxInfo.province,
city: wxInfo.city,
phone: null,
weixin: null,
dateBirth: null,
unit: null,
education: null,
specialty: null,
hobby: null,
height: 0,
weight: 0,
bloodType: null,
constellation: null,
currentLocation: null,
jobType: null,
motto: null,
photos: [],
beLikes: 0,
adoptedIds: [],
certification: false,
certId: null
})
info.save((err)=> {
if(err) return res.send({code: 500, errMsg: err, data: [] })
jwt.sign({userId: info._id, opId: info.openId},
youyuanSalt,
{expiresIn: '10d'},
(err, token)=> {
if(err) return res.send({code: 500, errMsg: err, data: [] })
res.send({code: 201, errMsg: 'ok', data: {token: token} })
})
})
}
})
}
module.exports = setInfo
10 changes: 10 additions & 0 deletions routes/home.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const router = require('express').Router()
, host = require('../utils/host')

router.get('/', (req, res)=> {
res.json({
api: host.youyuan
})
})

module.exports = router
10 changes: 10 additions & 0 deletions routes/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = {
home: require('./home'),
wechat: require('./wechat'),
// admin: require('./admin'),
// wechatpay: require('./wechatpay'),
// period: require('./period'),
// field: require('./field'),
// site: require('./site'),
// place: require('./place')
}
36 changes: 36 additions & 0 deletions routes/wechat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const router = require('express').Router()
, request = require('superagent')
, Apis = require('../utils/Apis')
, WXBizDataCrypt = require('../utils/WXBizDataCrypt')
// , checkYouYuan = require('../utils/checkYouYuan')
, setInfo = require('./functions/wechat/setInfo')
, youyuanId = process.env.YY_ID
, youyuanSecret = process.env.YY_SECRET

// checkYouYuan(router)

router.get('/login', (req, res)=> {
const code = req.query.code
, iv = req.query.iv
, encryptedData = req.query.encryptedData
if (!code || !iv || !encryptedData)
return res.send({message: 'Missing Query String!'})
request.get(`${Apis.session}?appid=${youyuanId}&secret=${youyuanSecret}&js_code=${code}&grant_type=authorization_code`)
.end((err, result)=> {
if(!JSON.parse(result.text).errcode) {
const sessionKey = JSON.parse(result.text).session_key
const pc = new WXBizDataCrypt(youyuanId, sessionKey)
const wxInfo = pc.decryptData(encryptedData, iv)
delete wxInfo.watermark
// console.log(wxInfo)
setInfo(wxInfo, res)
} else res.send({code: 500, errMsg: result.text, data: [] })
})
})

// router.get('/YYhash', (req, res)=> {
// var YYHash = makeHash(YY)
// res.send({code: 200, errMsg: 'hash', data: YYHash})
// })

module.exports = router
33 changes: 33 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const express = require('express')
, server = express()

require('./mongodb')
require('dotenv').config()

const cors = require('cors')
, bodyParser = require('body-parser')
server.use(cors())
server.use(bodyParser.json())
server.use(bodyParser.urlencoded({ extended: false }))
// server.use('/public', express.static('public'))

const port = process.env.PORT
, routes = require('./routes')
, wsocket = require('./wsocket')
// , kicker = require('./routes/kickerRoutes')

server.use('/', routes.home)
server.use('/wechat', routes.wechat)
// server.use('/kicker', kicker)
// server.use('/admin', routes.admin)
// server.use('/wechatpay', routes.wechatpay)
// server.use('/period', routes.period)
// server.use('/field', routes.field)
// server.use('/site', routes.site)

const socketServer = wsocket(server)

socketServer.listen(port, ()=> {
console.log('Server is ruuning on port: ' + port)
console.log('Use Ctrl-C to stop')
})
9 changes: 9 additions & 0 deletions utils/Apis.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = {
session: 'https://api.weixin.qq.com/sns/jscode2session',
token: 'https://api.weixin.qq.com/cgi-bin/token',
qrcode: 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode',
send: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send',
code: 'https://open.weixin.qq.com/connect/qrconnect',
oauth: 'https://api.weixin.qq.com/sns/oauth2/access_token',
map: 'http://apis.map.qq.com/ws/geocoder/v1/'
}
27 changes: 27 additions & 0 deletions utils/WXBizDataCrypt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
var crypto = require('crypto')

function WXBizDataCrypt(appId, sessionKey) {
this.appId = appId
this.sessionKey = sessionKey
}

WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
var sessionKey = new Buffer(this.sessionKey, 'base64')
encryptedData = new Buffer(encryptedData, 'base64')
iv = new Buffer(iv, 'base64')
try {
var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
decipher.setAutoPadding(true)
var decoded = decipher.update(encryptedData, 'binary', 'utf8')
decoded += decipher.final('utf8')
decoded = JSON.parse(decoded)
} catch (err) {
throw new Error(err)
}
if (decoded.watermark.appid !== this.appId) {
throw new Error('Illegal Buffer')
}
return decoded
}

module.exports = WXBizDataCrypt
Loading

0 comments on commit ad884d3

Please sign in to comment.