Strategy
1.0.0
該儲存庫是一個使用 Nodejs、Express、MongoDB 和 Ajax 的應用程式軟體,該應用程式包含使用 Express 建立的 API 和使用 Passport 的身份驗證。
最好使用 Nodejs v10.3、Express、Mongoose、Passport、Bcrypt、Express-Validator、Connect-Flash、Express-Handlebars 等。
最好使用 MongoDB。
使用 Postman 或 RestEasy 提供 api。
$ git clone https://github.com/DanielArturoAlejoAlvarez/Strategy.git [NAME APP]
$ npm install
$ npm start
請按照以下步驟操作,一切順利!重要的:
...
router . post ( '/register' , ( req , res ) => {
let { name , email , username , password , password2 , avatar , role , age , state } = req . body
//Validations
req . checkBody ( 'name' , 'Name is required' ) . notEmpty ( )
req . checkBody ( 'email' , 'Email is not valid' ) . isEmail ( )
req . checkBody ( 'username' , 'Username is required' ) . notEmpty ( )
req . checkBody ( 'password' , 'Password is required' ) . notEmpty ( )
req . checkBody ( 'password2' , 'Password do not match' ) . equals ( req . body . password )
req . checkBody ( 'avatar' , 'Avatar is required' ) . notEmpty ( )
req . checkBody ( 'role' , 'Role is required' ) . isNumeric ( )
req . checkBody ( 'age' , 'Age is required' ) . isNumeric ( )
req . checkBody ( 'state' , 'State is required' ) . isBoolean ( )
let errors = req . validationErrors ( )
if ( errors ) {
res . render ( 'register' , {
errors : errors
} )
} else {
let newUser = new User ( {
name : name ,
email : email ,
username : username ,
password : password ,
avatar : avatar ,
role : role ,
age : age ,
state : state
} )
User . createUser ( newUser , ( err , user ) => {
if ( err ) throw err
console . log ( user )
} )
req . flash ( 'success_msg' , 'You are registered and can now login.' )
res . redirect ( '/users/login' )
}
} )
. . .
...
const UserSchema = new Schema ( {
username : {
type : String ,
index : true
} ,
password : {
type : String
} ,
email : {
type : String
} ,
name : {
type : String
} ,
avatar : {
type : String
} ,
role : {
type : Number
} ,
age : {
type : Number
} ,
state : {
type : Boolean
}
} )
const User = module . exports = mongoose . model ( 'User' , UserSchema )
module . exports . createUser = function ( newUser , callback ) {
bcrypt . genSalt ( 10 , function ( err , salt ) {
bcrypt . hash ( newUser . password , salt , function ( err , hash ) {
newUser . password = hash
newUser . save ( callback )
} )
} )
}
. . .
...
//Session
app . use ( session ( {
secret : 'mysecretkey' ,
saveUninitialized : true ,
resave : true
} ) )
//Passport init
app . use ( passport . initialize ( ) )
app . use ( passport . session ( ) )
//Validator
app . use ( expressValidator ( {
errorFormatter : function ( param , msg , value ) {
var namespace = param . split ( '.' ) ,
root = namespace . shift ( ) ,
formParam = root
while ( namespace . length ) {
formParam += '[' + namespace . shift ( ) + ']'
}
return {
param : formParam ,
msg : msg ,
value : value
}
}
} ) )
. . .
歡迎在 GitHub 上提交錯誤報告和拉取請求:https://github.com/DanielArturoAlejoAlvarez/Strategy。該計畫旨在成為一個安全、溫馨的協作空間,貢獻者應遵守貢獻者契約行為準則。
該 gem 根據 MIT 授權條款作為開源提供。