我在 7 天内完成了自学微信全栈编程:使用 NodeJS 和使用羽毛 v2 的微信小程序。书中的认证是:
const authentication = require('@feathersjs/authentication')
const jwt = require('@feathersjs/authentication-jwt')
const local = require('@feathersjs/authentication-local')
const { Verifier } = require('@feathersjs/authentication-jwt')
const errors = require('@feathersjs/errors')
const rp = require('request-promise-native')
const crypto = require('crypto')
console.log('This is the print out of Verifier',typeof authentication)
// console.log('This is the print out of Verifier',local)
const appId = '...'
const appSecret = '...'
class CustomVerifier extends Verifier {
verify(req, email,password, done) {//email and password are ignored
if (!req.query.code || !req.query.encryptedData || !req.query.iv){
return Promise.reject(new errors.BadRequest(
'Error in authentication: missing referId, code, encryptedData or iv'))
}
let decoded = null
let openId = null
let userInfo = null
return rp({
uri: 'https://api.weixin.qq.com/sns/jscode2session'+`?appid=${appId}&secret=${appSecret}&js_code=${req.query.code}&grant_type=authentication_code`,
json: true
})
.then(res => {
let sessionKey = new Buffer(res.session_key,'base64')
let newEncryptedData = new Buffer(req.query.encryptedData,'base64')
let newIv = new Buffer(req.query.iv,'base64')
try{
let decipher = crypto.createDecipheriv('aes-128-cbc',sessionKey, newIv)
decipher.setAutoPadding(true)
decoded = decipher.update(newEncryptedData,'binary','utf8')
decoded += decipher.final('utf8')
decoded = JSON.parse(decoded)
} catch(err){
return Promise.reject(new errors.BadRequest('Error in wxDecode when decoding:',err))
}
openId = decoded.openId
userInfo = {
wxAvatarUrl: decoded.avatarUrl,
wxNickName : decoded.nickName,
bMale : decoded.gender == 1,
wxLanguage : decoded.language,
wxCity : decoded.city,
wxProvince : decoded.province,
wxCountry : decoded.country,
}
return this.service.find({ query: {wxOpenId: openId, $limit: 1}})
})
.then(res =>{
if (res.data.length > 0 )
return this.service.patch(res.data[0].id, userInfo)
else // new user
return this.service.create(Object.assign(userInfo, { wxOpenId: openId}))
})
.then(res =>{
let id = res.id
let payload = {[`${this.options.entity}Id`]:id}
done(null,res,payload)
})
.catch(err => {
done(err)
})
}
}
module.exports = function(){
const app = this
console.log('This is the print out of apppp ',app)
const config = app.get('authentication')
console.log('This is the print out of conggggg ',config)
app.configure(authentication().authenticate)
app.configure(jwt({ Verifier: CustomVerifier }))
app.configure(local(config.local))
app.service('authentication').hooks({
before: {
create: [authentication.hooks.authenticate(config.strategies)],
remove: [authentication.hooks.authenticate('jwt')]
}
})
}
作者 Jeff Ma 慷慨地向我发送了羽毛 v4 的认证如下:
const { AuthenticationService, JWTStrategy } = require('@feathersjs/authentication')
const { LocalStrategy } = require('@feathersjs/authentication-local')
const { expressOauth } = require('@feathersjs/authentication-oauth')
class MyAuthService extends AuthenticationService{
async getPayload(authResult, params){
const payload = await super.getPayload(authResult, params)
const {user} = authResult
if (user) {
user.serverPrefix = this.app.get('serverPrefix')
payload.user = user
}
return payload
}
async authenticate(data, params, ...strategies){
if (data.strategies === 'local'){ // not 'jwt
if (data.type !== 'account' && data.username === 'system'){
throw new Error ('Only the special people can come in ')
}
}
return super.authenticate(data, params, ...strategies)
}
}
module.exports = app => {
const authentication = new MyAuthService(app)
authentication.register('jwt', new JWTStrategy())
authentication.register('local', new LocalStrategy())
app.use('/authentication', authentication)
app.configure(expressOauth())
}
我是使用 NodeJS、npm、feathers 和小程序的这个框架的新手。我用 Django 和 Python 做了一些工作。
启动服务器时,出现以下错误:
info: Feathers application started on http://localhost:3030
info: Method `find` is not supported by this endpoint. {"type":"FeathersError","name":"MethodNotAllowed","code":405,"className":"method-not-allowed","errors":{}}
来自小程序(客户端)的错误:
VM16 asdebug.js:1 POST http://localhost:3030/authentication 500 (Internal Server Error)
failed to call authentication: {error: "failed to login"}
index.js? [sm]:67 init-login err: {error: "failed to login"}
我已经做了很多搜索和实验,但我被卡住了。您能否给我任何见解或指向我的教程?
谢谢你。