Exemple #1
0
exports.login = function*() {
  let {login, password} = this.request.body;

  if (!(login && password)) {
    this.throw(400, 'login and password are required');
  }

  let user = yield User.findOne({
    where: { login: login }
  });

  if (!(user && user.authenticate(password))) {
    this.throw(401, 'Неверные логин или пароль');
  }

  if (user.isBlocked) {
    this.throw(401, 'Пользователь заблокирован');
  }

  let token = jwt.sign(user.toJSON(), jwtSecret);

  this.body = extend(user.toJSON(), {
    token: token
  });
};
Exemple #2
0
module.exports = co.wrap(function *(ctx) {
  const email = ctx.request.body.email
  const password = ctx.request.body.password

  const user = yield User.findOne({
    where: { email: email }
  })
  const isCorrect = !!user && (yield user.comparePassword(password))
  if (!isCorrect) {
    ctx.status = 401
    ctx.body = {
      error: 'Invalid username or password.'
    }
    return
  }

  const token = jwt.sign({
    id: user.id,
    email: user.email,
    role: user.role
  }, constants.SESSION_SECRET, {
    expiresInMinutes: constants.SESSION_EXPIRY
  })
  ctx.body = {
    token: token
  }
})
Exemple #3
0
function* forgotPassword(next) {
    var token;
    let forgotDesc = this.request.body.fields;
    let email = forgotDesc.email;
    if (email) {
        email = email.toLowerCase();
        try {
            let user = yield User.findOne({ email: email }).exec();
            if (user) {
                token = jwt.sign({ email: user.email }, config.app.privateKey, { 'algorithms': ['HS256'], 'expiresIn': '1h' });
                l.info(token);
            }
            var emailJson = {
                to: email,
                from: '*****@*****.**',
                subject: 'Gemini Survey Password Reset',
                text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
                    'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
                    "http://" + this.request.header.host + '/' + user.name.first + '/password/reset/' + token + '\n\n' +
                    'If you did not request this, please ignore this email and your password will remain unchanged.\n'
            };
            var semail = new sendgrid.Email(emailJson);
            sendgrid.send(semail, function (err, json) {
                if (err) {
                    return console.error(err);
                }
                console.log(json);
            });
        }
        catch (err) {
            this.log.info("error in sending mail");
        }
    }
}
  it('Should respond with status 200 and todos object', (done) => {
    // store request client in agent variable
    // to re-use it later on
    const agent = request(app.listen())

    // simulate token
    const token = koajwt.sign({}, JWT_SECRET, { expiresIn: JWT_TTL })
    agent
    .get('/api/todos')
    .set('Authorization', `Bearer ${token}`)
    .expect('Content-Type', /json/)
    .expect(200)
    .expect((res) => {
      assert(Array.isArray(res.body), 'Response should be array of todos')
    })
    .end((err, res) => {
      const testtext = 'updated todo in unit test'
      const { text, ...other } = res.body[0]
      const send = Object.assign({}, {...other}, {text: testtext})
      /**
       * start nested request
       */
      agent
      .put('/api/todos')
      .set('Authorization', `Bearer ${token}`)
      .send(send)
      .expect('Content-Type', /json/)
      .expect(200)
      .expect((res) => {
        assert(res.body.text === testtext, `"text" should be "${testtext}"`)
        assert.property(res.body, '_id', 'Should have property "_id"')
      })
      .end(done)
    })
  })
Exemple #5
0
  handler: function* () {
    var params = this.request.body;
    var user = yield this.users.findOne({
      email: params.email
    });

    if (user) {
      var match = yield pswd.compare(params.password, user.password);
      if (match) {
        var token = jwt.sign(user, process.env.JWT_KEY, {
          expiresInMinutes: 60 * 5
        });
				delete user.password;
        this.body = {
          token: token,
          user: user
        };
				return;
      }
    }

    this.status = 401;
    this.body = {
      error: 'Wrong user or password'
    };
    return;
  }
Exemple #6
0
function authorize(user) {
  delete user.password;
  return {
    token: jwt.sign(user, process.env.JWT_KEY, { expiresInMinutes: 60 * 5 }),
    user: user,
  }
}
Exemple #7
0
router.post('/public/api/user/login', function* (next) {
    var user = yield parse(this);
    if (!user.username || !user.password) {
        this.throw(401, JSON.stringify({ error: 'Incorrect username or password' }));
        return yield next;
    }
    var users = yield this.pg.db.client.query_(`Select username, hash, id from "users" where "username" = ($1)`, [user.username]);
    users = users.rows;
    if (users.length === 0) {
        this.throw(401, JSON.stringify({ error: 'Incorrect username or password' }));
        return yield next;
    } else {
        if (yield bcrypt.compare(user.password, users[0].hash)) {
            var token = jwt.sign({ "user": users[0].username, id: users[0].id }, secret);
            users[0].token = token;
            delete users[0].hash;
            this.body = users[0];
            this.status = 200;
            return yield next;
        } else {
            this.throw(401, JSON.stringify({ error: 'Incorrect username or password' }));
            return yield next;
        }
    }
});
module.exports = function (user) {
  var payload = {
    user: user,
    iat: new Date().getTime(),
    exp: moment().add(7, 'days').valueOf()
  };
  return jwt.sign(payload, environment.default.secret, {expiresInMinutes: 90 * 24 * 60 /* 90 days */});
}
Exemple #9
0
const refresh = ctx => {
  const token = jwt.sign(ctx.state.user, constants.SESSION_SECRET, {
    expiresInMinutes: constants.SESSION_EXPIRY
  })
  ctx.body = {
    token: token
  }
}
Exemple #10
0
const tokenInfo = () => {
  return {
    authenticated: true,
    token: jwt.sign({
      username: userInfo.email
    }, jwtSecret)
    //token: Math.random().toString(36).substring(7)
  }
}
Exemple #11
0
app.use(function *(next) {
	if (this.url.match(/^\/login/)) {
		var claims = yield parse(this);
		var token = jwt.sign(claims, privateKey, {algorithm: 'RS256'});
		this.status = 200;
		this.body = {token: token};
	} else {
		yield next;
	}
});
Exemple #12
0
function* verifyUser(next) {
    try {
        let name = this.params.name;
        let token = this.params.token;
        let decryptToken = jwt.verify(token, config.app.privateKey, { 'algorithms': ['HS256'] });
        let user = yield User.findOne({ email: decryptToken.email }).exec();
        let tokenNew = jwt.sign({ email: user.email }, config.app.privateKey, { 'algorithms': ['HS256'], 'expiresIn': '1h' });
        this.response.set('Access-Control-Expose-Headers', 'authorization');
        this.response.set('authorization', jwt.sign({ _id: user._id, sTime: Date.now() }, config.app.privateKey));
        this.cookies.set('survey', this.response.authorization);
        this.body = { "url": "", "msg": "Hi " + user.name.first + ",\n\nYour account has been verified" };
        this.status = 200;
    }
    catch (err) {
        this.log.info(logmeta, 'Error in verifying User Detail: ', { err: err });
        this.status = err.status || 500;
        this.body = err.message;
        this.app.emit('error', err, this);
    }
}
Exemple #13
0
router.post('/reauth', function*(){
	let { id, name } = this.state
	let user = yield User.findOne({ id })
	let resp = { message: "Can't reauth!" }

	if(user != null){
		resp = { message: "You cheked successfully.", token: jwt.sign({ name: name, id: user.id }, secret, secret, { expiresIn: "24 hours" }) }
	}

	this.body = resp
})
Exemple #14
0
router.post('/token-refresh', async (ctx, next) => {
  const token = ctx.request.body.token
  let decoded = false

  try {
    decoded = jwt.verify(token, process.env.SESSION_SECRET)
  } catch (err) {
    ctx.status = 401
    ctx.body = { error: err }

    return
  }

  const query = User.where({ _id: decoded.username })
  let user = false

  try {
    user = await query.findOne()
  } catch (err) {
    log('Couldn\'t load user', err)
  }

  if (!user) {
    ctx.status = 401

    ctx.body = {
      error: 'User doesn\'t exist'
    }

    return
  }

  const isMatch = user.tryPassword(decoded.password)

  if (isMatch) {
    ctx.body = {
      token: jwt.sign(decoded, process.env.SESSION_SECRET, {
        expiresIn: 300
      })
    }

    return
  }

  ctx.status = 401

  ctx.body = {
    error: 'Wrong password'
  }

  await next()
})
Exemple #15
0
export const signin = async ctx => {
  const { userName } = ctx.request.body;

  if (userName !== 'oab admin') {
    ctx.throw(400, 'Unknown user name or password');
  }

  ctx.body = {
    token: jwt.sign({
      id: 'TODO place user id here',
    }, config.jwt_shared_secret),
  };
};
Exemple #16
0
router.post('/token-auth', async (ctx, next) => {
  const body = ctx.request.body

  if (!body.username || !body.password) {
    ctx.status = 400
    ctx.body = {
      error: 'User and/or password empty'
    }

    return
  }

  const query = User.where({ _id: body.username })
  let user = false

  try {
    user = await query.findOne()
  } catch (err) {
    log('Couldn\'t load user', err)
  }

  if (!user) {
    ctx.status = 400

    ctx.body = {
      error: 'User doesn\'t exist'
    }

    return
  }

  // Compare password with the one within the DB
  const isMatch = user.tryPassword(body.password)

  if (isMatch) {
    const token = jwt.sign(body, process.env.SESSION_SECRET, {
      expiresIn: 300
    })

    ctx.body = { token }
    return
  }

  ctx.status = 400

  ctx.body = {
    error: 'Wrong password'
  }

  await next()
})
exports.index = function* () {
    var privateKey = fs.readFileSync('jwt.rsa');
    var credential = yield parse(this);
    // Validate credential
    if (!(credential.username && credential.password))
        this.throw(400, "Invalid credential");

    var test = yield validate(credential.username, credential.password);
    if (!test) this.throw(400, "Invalid credential");

    var token = jwt.sign(credential, privateKey, { algorithm: 'RS256', exp: config.getExpiration() });
    this.status = 200;
    this.body = { token: token };
};
 return (ctx, next) => {
     var token = "";
     if (jwt) {
         var secret = jwt && jwt.secret;
         var expiresIn = jwt && jwt.expiresIn;
         var openid = ctx.request.body.openid;
         // get user info from openid.
         var info = { openid: openid };
         token = KoaJwt.sign(info, secret, { expiresIn: expiresIn });
         //var token = KoaJwt.sign({ id: 123 }, 'mysecret', { expiresIn: 60*60 });
         console.log ("token", token);
     }
     ctx.body = { jwt: token };
 };
Exemple #19
0
exports.post_signin = async (ctx, next) =>{
  let body = ctx.request.body

  let crypto = require('crypto');
  let pwd = crypto.createHash('md5').update(body.pwd).digest('hex');

  let mem = await Table.Mem.where({email: body.email, pwd: pwd}).fetch()
  if (mem) {
    ctx.cookies.set('mem', jwt.sign({uid: mem.id}, localEnv.jwtkey))
    ctx.body = true
  }else{
    ctx.body = false
  }

}
Exemple #20
0
router.post('/login', function *() {
	let { name, pass } = this.request.body
	let user
	
	user = yield User.findOne( { name: name } ).exec()
	
	let resp = { message: "Your username and/or password is incorrect!" }

	if (user != null) {
		if(user.checkPassword(pass)){
			resp = { message: "You are logged in successfully.", token: jwt.sign({ name: name, id: user.id }, secret, { expiresIn: "24 hours" }) }
		}

	}
	this.body = resp
	
})
export function* login() {
  const { username, password } = this.request.body
  if (!username) this.throw(400, 'Require username')
  if (!password) this.throw(400, 'Require password')

  const user = find(users, item => item.username === username && item.password === password)
  if (!user) {
    debug('Authentication fail')
    this.throw(401)
  }

  debug('Got User:', user)

  const token = jwt.sign({ username, scopes: user.scopes }, secret)
  debug(token)
  this.status = 200
  this.body = { token }
}
Exemple #22
0
/**
 * Retrieves the user credentials and returns a JSON Web Token along with user profile info in JSON format.
 */
function *signin() {
  var credentials = yield parse(this);
  var user = yield mongo.users.findOne({email: credentials.email}, {email: 1, name: 1, password: 1});

  if (!user) {
    this.throw(401, 'Incorrect e-mail address.');
  } else if (user.password !== credentials.password) {
    this.throw(401, 'Incorrect password.');
  } else {
    user.id = user._id;
    delete user._id;
    delete user.password;
    user.picture = 'api/users/' + user.id + '/picture';
  }

  // sign and send the token along with the user info
  var token = jwt.sign(user, config.app.secret, {expiresInMinutes: 90 * 24 * 60 /* 90 days */});
  this.body = {token: token, user: user};
}
 it('Should respond with status 200 and todos object', (done) => {
   // simulate token
   const token = koajwt.sign({}, JWT_SECRET, { expiresIn: JWT_TTL })
   request(app.listen())
   .post('/api/todos')
   .set('Authorization', `Bearer ${token}`)
   .send({
     text: 'unit test call',
     completed: false,
     weight: 0
   })
   .expect('Content-Type', /json/)
   .expect((res) => {
     assert(res.body.text === 'unit test call', '"text" should be "unit test call"')
     assert(res.body.completed === false, '"completed" should be false')
     assert(res.body.weight === 0, '"weight" should be 0')
     assert.property(res.body, '_id', 'Should have property "_id"')
   })
   .end(done)
 })
Exemple #24
0
 router.post(`${prefix}/login`, async (ctx) => {
   const login = (ctx.request.body.login) ? ctx.request.body.login.trim() : '';
   const password = (ctx.request.body.password) ? ctx.request.body.password.trim() : '';
   const hash = crypto.createHash('md5').update(password).digest('hex');
   let user;
   try {
     user = await userModel.findOne({ login, password: hash });
   }
   catch(err) {
     ctx.status = err.status || 500;
     ctx.body = 'Internal server error';
   }
   if (user) {
     const token = jwt.sign({ login: user.login }, JWT_SECRET_STRING);
     ctx.body = { token };
   } else {
     ctx.status = 401;
     ctx.body = 'Wrong credentials';
   }
 });
Exemple #25
0
function *googleCallback() {
  if (this.query.error) {
    this.redirect('/signin');
    return;
  }

  // get an access token from google in exchange for oauth code
  var tokenResponse = yield request.post('https://accounts.google.com/o/oauth2/token', {form: {
    code: this.query.code,
    client_id: config.oauth.google.clientId,
    client_secret: config.oauth.google.clientSecret,
    redirect_uri: config.oauth.google.callbackUrl,
    grant_type: 'authorization_code'
  }});
  var token = JSON.parse(tokenResponse.body);
  if (!token.access_token) {
    this.redirect('/signin');
    return;
  }

  // get user profile (including email address) from facebook and save user data in our database if necessary
  var profileResponse = yield request.get('https://www.googleapis.com/plus/v1/people/me?access_token=' + token.access_token);
  var profile = JSON.parse(profileResponse.body);
  var user = yield mongo.users.findOne({email: profile.emails[0].value}, {email: 1, name: 1});
  if (!user) {
    user = {
      _id: (yield mongo.getNextSequence('userId')),
      email: profile.emails[0].value,
      name: profile.displayName,
      picture: (yield request.get(profile.image.url, {encoding: 'base64'})).body
    };
    var results = yield mongo.users.insert(user);
  }

  // redirect the user to index page along with user profile object as query string
  user.id = user._id;
  delete user._id;
  user.picture = 'api/users/' + user.id + '/picture';
  var token = jwt.sign(user, config.app.secret, {expiresInMinutes: 90 * 24 * 60 /* 90 days */});
  this.redirect('/?user=' + encodeURIComponent(JSON.stringify({token: token, user: user})));
}
Exemple #26
0
exports.register = function*() {
  let currentRegToken = yield regToken();

  if (this.request.body.regToken !== currentRegToken) {
    this.throw(401, 'Invalid registration token');
  }

  let user = User.build(this.request.body);

  try {
    yield user.save();
  } catch(err) {
    this.throw(400, err.message);
  }

  let token = jwt.sign(user.toJSON(), jwtSecret);

  this.body = extend(user.toJSON(), {
    token: token
  });
};
Exemple #27
0
/**
 * Facebook OAuth 2.0 callback endpoint.
 */
function *facebookCallback() {
  if (this.query.error) {
    this.redirect('/signin');
    return;
  }

  // get an access token from facebook in exchange for oauth code
  var tokenResponse = yield request.get(
          'https://graph.facebook.com/oauth/access_token?client_id=' + config.oauth.facebook.clientId +
          '&redirect_uri=' + config.oauth.facebook.callbackUrl +
          '&client_secret=' + config.oauth.facebook.clientSecret +
          '&code=' + this.query.code);
  var token = qs.parse(tokenResponse.body);
  if (!token.access_token) {
    this.redirect('/signin');
    return;
  }

  // get user profile (including email address) from facebook and save user data in our database if necessary
  var profileResponse = yield request.get('https://graph.facebook.com/me?fields=name,email,picture&access_token=' + token.access_token);
  var profile = JSON.parse(profileResponse.body);
  var user = yield mongo.users.findOne({email: profile.email}, {email: 1, name: 1});
  if (!user) {
    user = {
      _id: (yield mongo.getNextSequence('userId')),
      email: profile.email,
      name: profile.name,
      picture: (yield request.get(profile.picture.data.url, {encoding: 'base64'})).body
    };
    var results = yield mongo.users.insert(user);
  }

  // redirect the user to index page along with user profile object as query string
  user.id = user._id;
  delete user._id;
  user.picture = 'api/users/' + user.id + '/picture';
  var token = jwt.sign(user, config.app.secret, {expiresInMinutes: 90 * 24 * 60 /* 90 days */});
  this.redirect('/?user=' + encodeURIComponent(JSON.stringify({token: token, user: user})));
}
Exemple #28
0
userController.login = function *login() {
  var credentials = this.request.body;

  var validateResult = Joi.validate(credentials, UserValidation.userSchema);
  if (validateResult.error) {
    this.throw(400, validateResult.error.details[0].message);
  }

  var user = yield UserModel.findByEmail(credentials.email);
  if (!user) {
    this.throw(400, 'Incorrect e-mail address.');
  }

  var isMatch = yield bcrypt.compare(credentials.password, user.password);
  if (!isMatch) {
    this.throw(400, 'Incorrect password.');
  }

  var payload = {sub: user.id};
  var token = jwt.sign(payload, config.app.secret, {expiresIn: 30 * 24 * 60 * 60});
  this.state.user = user;
  this.body = {token: token};
};
Exemple #29
0
export default async function login (ctx, next) {
  const body = ctx.request.body
  const { email, password } = body

  const user = await User.findOne({email: email.toLowerCase()})
  ctx.assert(user, 401, 'Wrong email or password')

  const correctPassword = await compare(password, user.password)
  ctx.assert(correctPassword, 401, 'Wrong email or password')

  const token = jwt.sign({
    email: user.email,
    roles: user.roles
  }, config.jwt.secret)

  user.lastLogin = new Date()
  await user.save()

  ctx.body = {
    success: true,
    token
  }
}
Exemple #30
0
'use strict';

var config = require('../../server/config/config'),
    mongoSeed = require('../../server/config/mongo-seed'),
    app = require('../../app'),
    jwt = require('koa-jwt'),
    baseUrl = 'http://*****:*****@koanjs.com'}, config.app.secret);
token = 'Bearer ' + token;

// make request and token objects available
exports.request = request;
exports.token = token;

// initiate KOAN server before each test is run
// also drop and re-seed the test database before each run
console.log('Mocha starting to run server tests on port ' + config.app.port);
beforeEach(function (done) {
  mongoSeed(true);
  app.init(done);
});

// close the server after each test is done
afterEach(function (done) {
  app.server.close(done);
});