Skip to content

Commit 7a1e096

Browse files
committed
Add new project
0 parents  commit 7a1e096

File tree

13 files changed

+5742
-0
lines changed

13 files changed

+5742
-0
lines changed

.eslintrc.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
module.exports = {
2+
env: {
3+
browser: true,
4+
es6: true,
5+
},
6+
extends: [
7+
'airbnb-base',
8+
],
9+
globals: {
10+
Atomics: 'readonly',
11+
SharedArrayBuffer: 'readonly',
12+
},
13+
parserOptions: {
14+
ecmaVersion: 2018,
15+
},
16+
rules: {
17+
},
18+
};

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
node_modules/
2+
config/

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
https://server-koa.herokuapp.com/

controllers/index.js

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
const passport = require('koa-passport');
2+
const config = require('config');
3+
const jwt = require('jwt-simple'); // аутентификация по JWT для hhtp
4+
const User = require('../models/User');
5+
6+
module.exports = {
7+
async signIn(ctx, next) {
8+
await passport.authenticate('local', (err, user) => {
9+
if (user) {
10+
const payload = {
11+
id: user._id,
12+
};
13+
ctx.body = {
14+
token: jwt.encode(payload, config.get('jwtSecret')),
15+
};
16+
} else {
17+
console.log(err);
18+
}
19+
})(ctx, next);
20+
},
21+
async signUp(ctx) {
22+
const {
23+
firstname,
24+
lastname,
25+
email,
26+
username,
27+
password,
28+
} = ctx.request.body;
29+
try {
30+
const Find = await User.find({
31+
email,
32+
});
33+
if (Find.length !== 0) {
34+
ctx.body = {
35+
msg: 'same person already exist',
36+
};
37+
} else {
38+
const newUser = new User({
39+
firstname,
40+
lastname,
41+
username,
42+
email,
43+
password,
44+
});
45+
const res = await User.create(newUser);
46+
ctx.response.status = 200;
47+
}
48+
} catch (err) {
49+
throw err;
50+
}
51+
},
52+
async reset1(ctx, next) {
53+
const {
54+
email,
55+
} = ctx.request.body;
56+
try {
57+
const Find = await User.find({
58+
email,
59+
});
60+
if (Find.length === 0) {
61+
console.log('there is no such person');
62+
} else {
63+
ctx.response.status = 200;
64+
}
65+
} catch (err) {
66+
throw err;
67+
}
68+
},
69+
async reset2(ctx, next) {
70+
const {
71+
email,
72+
password,
73+
} = ctx.request.body;
74+
try {
75+
const Find = await User.find({
76+
email,
77+
});
78+
console.log(Find);
79+
user = Find[0];
80+
user.password = password;
81+
await user.save();
82+
ctx.response.status = 200;
83+
} catch (err) {
84+
throw err;
85+
}
86+
},
87+
async getPersonal(ctx) {
88+
ctx.body = 'Secret content';
89+
},
90+
91+
};

index.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
const Koa = require('koa');
2+
const KoaRouter = require('koa-router');
3+
// const serve = require('koa-static');
4+
const logger = require('koa-logger');
5+
const bodyParser = require('koa-bodyparser');
6+
const cors = require('koa2-cors');
7+
const passport = require('./libs/passport/index');
8+
require('./libs/mongoose');
9+
10+
passport.initialize();
11+
12+
const app = new Koa();
13+
const router = new KoaRouter();
14+
app.use(cors({
15+
origin() {
16+
return '*';
17+
},
18+
}));
19+
20+
app.use(async (ctx, next) => {
21+
try {
22+
console.log('Request', ctx.request);
23+
await next();
24+
} catch (err) {
25+
console.log('Global error: ', err);
26+
ctx.status = 500;
27+
ctx.body = {
28+
error: true,
29+
};
30+
}
31+
});
32+
app.use(logger());
33+
app.use(bodyParser());
34+
35+
app.use(passport.initialize());
36+
37+
const auth = require('./routes/auth').routes();
38+
39+
router.use('/api/', auth);
40+
app.use(router.routes())
41+
.use(router.allowedMethods());
42+
43+
44+
const PORT = process.env.PORT || 7070;
45+
app.listen(PORT, (error) => {
46+
if (error) console.log('error');
47+
else console.log(`server on port ${PORT}`);
48+
});

libs/mongoose.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const config = require('config');
2+
const mongoose = require('mongoose'); // стандартная прослойка для работы с MongoDB
3+
4+
mongoose.Promise = Promise; // Просим Mongoose использовать стандартные Промисы
5+
mongoose.set('debug', true); // Просим Mongoose писать все запросы к базе в консоль
6+
mongoose.connect( config.get('databaseUrl'),
7+
{ useNewUrlParser: true, useFindAndModify: false, useCreateIndex: true },
8+
(err) => { if (err) throw new Error('Connected with db is faild'); console.log('connected'); });
9+
10+
module.exports = mongoose;

libs/passport/index.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
const passport = require('koa-passport');
2+
3+
passport.use(require('./jwtStrategy'));
4+
passport.use(require('./localStrategy'));
5+
6+
module.exports = passport;

libs/passport/jwtStrategy.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
const JwtStrategy = require('passport-jwt').Strategy;
2+
const ExtractJwt = require('passport-jwt').ExtractJwt; // авторизация через JWT
3+
const config = require('config');
4+
5+
const User = require('../../models/User');
6+
7+
let opts = {
8+
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('JWT'),
9+
secretOrKey: config.get('jwtSecret'),
10+
};
11+
12+
module.exports = new JwtStrategy(opts, (jwtPayload, done) => {
13+
User.findById(jwtPayload.id, (err, user) => {
14+
if (err) {
15+
return done(err, false);
16+
}
17+
if (user) {
18+
return done(null, user);
19+
}
20+
return done(null, false);
21+
});
22+
});
23+

libs/passport/localStrategy.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const LocalStrategy = require('passport-local');
2+
const User = require('../../models/User');
3+
// локальная стратегия авторизации
4+
5+
const opts = {
6+
usernameField: 'email',
7+
passwordField: 'password',
8+
passReqToCallback: true,
9+
session: false
10+
};
11+
12+
module.exports = new LocalStrategy(opts, (req, email, password, done) => {
13+
User.findOne({ email: email }, (err, user) => {
14+
if (err) {
15+
return done(err);
16+
}
17+
if (!user) {
18+
return done('User doesn\'t exist!', false);
19+
}
20+
if (!user.checkPassword(password)) {
21+
return done('Incorrect password!', false);
22+
}
23+
return done(null, user);
24+
});
25+
});

models/User.js

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
const mongoose = require('mongoose');
2+
const config = require('config');
3+
const crypto = require('crypto');
4+
// const beautifyUnique = require('mongoose-beautiful-unique-validation');
5+
6+
const User = mongoose.Schema;
7+
const UserSchema = new User({
8+
firstname: String,
9+
lastname: String,
10+
username: {
11+
type: String,
12+
// unique: 'Two users cannot share the same username ({VALUE})',
13+
required: 'add username',
14+
},
15+
email: {
16+
type: String,
17+
// unique: 'Two users cannot share the same email ({VALUE})',
18+
required: 'add e-mail',
19+
validate: {
20+
validator: function checkEmail(value) {
21+
const re = /^(\S+)@([a-z0-9-]+)(\.)([a-z]{2,4})(\.?)([a-z]{0,4})+$/;
22+
return re.test(value);
23+
},
24+
message: props => `${props.value} is not a valid email.`,
25+
},
26+
},
27+
photo: {
28+
type: String,
29+
default: config.get('defaultUserPhoto'),
30+
},
31+
token: String,
32+
passwordHash: String,
33+
salt: String,
34+
}, {
35+
timestamps: true,
36+
});
37+
UserSchema.virtual('password')
38+
.set(function (password) {
39+
if (!password) {
40+
this.invalidate('password', 'Password can\'t be empty!');
41+
}
42+
43+
if (password !== undefined) {
44+
if (password.length < 6) {
45+
this.invalidate('password', 'Password can\'t be less than 6 symbols!');
46+
}
47+
}
48+
49+
this._plainPassword = password;
50+
51+
if (password) {
52+
this.salt = crypto.randomBytes(config.get('crypto').hash.length).toString('base64');
53+
this.passwordHash = crypto.pbkdf2Sync(
54+
password,
55+
this.salt,
56+
config.get('crypto').hash.iterations,
57+
config.get('crypto').hash.length,
58+
'sha512',
59+
).toString('base64');
60+
} else {
61+
this.salt = undefined;
62+
this.passwordHash = undefined;
63+
}
64+
})
65+
66+
.get(function () {
67+
return this._plainPassword;
68+
});
69+
70+
UserSchema.methods.checkPassword = function (password) {
71+
if (!password) return false;
72+
if (!this.passwordHash) return false;
73+
return crypto.pbkdf2Sync(
74+
password,
75+
this.salt,
76+
config.get('crypto').hash.iterations,
77+
config.get('crypto').hash.length,
78+
'sha512',
79+
).toString('base64') === this.passwordHash;
80+
};
81+
82+
module.exports = mongoose.model('User', UserSchema);

0 commit comments

Comments
 (0)