私は7 日間で自分自身に WeChat フルスタック プログラミングを教えます: NodeJS と Feathers v2 を使用する WeChat MiniProgram を使用します。本の認証は次のとおりです。
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')]
}
})
}
著者のジェフ・マーは、以下のようにフェザー 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、フェザー、ミニプログラムを使用して、このフレームワークを初めて使用します。私は 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"}
私はかなりの検索と実験を行いましたが、行き詰まっています。何か洞察を与えたり、チュートリアルを教えてくれませんか?
ありがとうございました。