File tree 1 file changed +56
-20
lines changed
1 file changed +56
-20
lines changed Original file line number Diff line number Diff line change 1
- import { Schema , model } from 'mongoose' ;
1
+ import bcrypt from 'bcrypt-nodejs' ;
2
+ import { Document , Schema , Error , model } from 'mongoose' ;
3
+
4
+ export type UserDocument = Document & {
5
+ email : string ;
6
+ password : string ;
7
+
8
+ facebook : string ;
9
+ tokens : AuthToken [ ] ;
10
+
11
+ profile : {
12
+ name : string ;
13
+ gender : string ;
14
+ location : string ;
15
+ website : string ;
16
+ picture : string ;
17
+ } ;
18
+
19
+ } ;
20
+
21
+ export interface AuthToken {
22
+ accessToken : string ;
23
+ kind : string ;
24
+ }
2
25
3
26
const userSchema = new Schema ( {
4
- name : {
5
- type : String ,
6
- required : true ,
7
- unique : true ,
8
- } ,
9
- age : {
10
- type : Number ,
11
- required : true ,
12
- } ,
13
- married : {
14
- type : Boolean ,
15
- required : true ,
16
- } ,
17
- comment : String ,
18
- createdAt : {
19
- type : Date ,
20
- default : Date . now ,
21
- } ,
27
+ email : { type : String , unique : true } ,
28
+ password : String ,
29
+
30
+ facebook : String ,
31
+ twitter : String ,
32
+ google : String ,
33
+ tokens : Array ,
34
+
35
+ profile : {
36
+ name : String ,
37
+ gender : String ,
38
+ location : String ,
39
+ website : String ,
40
+ picture : String
41
+ }
42
+ } , { timestamps : true } ) ;
43
+
44
+ /**
45
+ * Password hash middleware.
46
+ */
47
+ userSchema . pre ( 'save' , function save ( next ) {
48
+ const user = this as UserDocument ;
49
+ if ( ! user . isModified ( 'password' ) ) { return next ( ) ; }
50
+ bcrypt . genSalt ( 10 , ( err , salt ) => {
51
+ if ( err ) { return next ( err ) ; }
52
+ bcrypt . hash ( user . password , salt , ( err : Error , hash ) => {
53
+ if ( err ) { return next ( err ) ; }
54
+ user . password = hash ;
55
+ next ( ) ;
56
+ } ) ;
57
+ } ) ;
22
58
} ) ;
23
59
24
- export default model ( 'User' , userSchema ) ;
60
+ export const User = model < UserDocument > ( 'User' , userSchema ) ;
You can’t perform that action at this time.
0 commit comments