This repository has been archived by the owner on Apr 7, 2021. It is now read-only.
/
auth.js
90 lines (69 loc) · 2.46 KB
/
auth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
'use strict';
var buffersEqual = require('buffer-equal-constant-time');
var utils = require('ssh2').utils;
var schemas = require('../schemas');
var mongoose = require('mongoose');
module.exports = function(userMeta) {
return function(ctx) {
console.log(' ** '+ctx.username+' initiated');
if(ctx.username === undefined) {
console.log(' ** rejecting nameless login', ctx.method);
ctx.reject();
return;
}
console.log(' ** authenticating with method', ctx.method);
if(ctx.method === 'keyboard-interactive') {
console.log(' ** keyboard-interactive auth is disabled');
ctx.reject();
}
var User = mongoose.model('User', schemas.user);
User.findOne({username: ctx.username}, function(err, doc){
if (doc) {
if (ctx.method === 'publickey'
&& ctx.username!=undefined
&& doc.publicKey
&& doc.publicKey.length !== 0) {
console.log(' ** trying key auth');
//load publickey by username
if(doc.publicKey && doc.publicKey.length) {
var publicKey = utils.genPublicKey(utils.parseKey(doc.publicKey));
var successfulKeyAuth = ctx.key.algo === publicKey.fulltype
&& buffersEqual(ctx.key.data, publicKey.public);
if (successfulKeyAuth) {
// user logged in via key, serve interface
console.log('[ok] key auth');
userMeta.next = 'auth';
userMeta.user = doc;
ctx.accept();
} else {
console.log('[no] key auth');
return ctx.reject();
}
} else {
console.log('[no] key auth');
return ctx.reject();
}
} else if(ctx.method === 'password') {
console.log(' ** trying password auth');
var hash = require('sha256');
if (doc && doc.hash == hash(ctx.password + doc.salt)) {
console.log('[ok] pass auth');
userMeta.next = 'auth';
userMeta.user = doc;
ctx.accept();
} else {
console.log('[no] pass auth');
ctx.reject();
}
}
ctx.reject(); // none
} else { //user not found, forward to shell for registration
console.log(' ** user does not exist, ask to register');
userMeta.next = "nouser";
userMeta.user = false;
userMeta.username = ctx.username;
ctx.accept();
}
});
}
}