3 * Copyright 2016 RIFT.IO Inc
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
20 * sessions api module. Provides API functions for sessions
21 * @module framework/core/modules/api/sessions
22 * @author Kiran Kashalkar <kiran.kashalkar@riftio.com>
25 var Promise
= require('bluebird');
26 var constants
= require('../../api_utils/constants');
27 var utils
= require('../../api_utils/utils');
28 var request
= utils
.request
;
29 var rp
= require('request-promise');
31 var _
= require('lodash');
32 var base64
= require('base-64');
33 var APIVersion
= '/v2';
34 var configurationAPI
= require('./configuration');
36 function logAndReject(mesg
, reject
) {
44 function logAndRedirectToLogin(mesg
, res
, req
) {
45 var api_server
= req
.query
['api_server'] || (req
.protocol
+ '://' + configurationAPI
.globalConfiguration
.get().api_server
);
46 var upload_server
= req
.protocol
+ '://' + (configurationAPI
.globalConfiguration
.get().upload_server
|| req
.hostname
);
48 res
.redirect('login.html?api_server=' + api_server
+ '&upload_server=' + upload_server
);
52 sessionsAPI
.create = function(req
, res
) {
53 var api_server
= req
.query
["api_server"];
54 var uri
= utils
.confdPort(api_server
);
55 var login_url
= uri
+ APIVersion
+ '/api/login';
56 var project_url
= uri
+ APIVersion
+ '/api/operational/project';
57 var authorization_header_string
= 'Basic ' + base64
.encode(req
.body
['username'] + ':' + req
.body
['password']);
58 return new Promise(function(resolve
, reject
) {
63 headers
: _
.extend({}, constants
.HTTP_HEADERS
.accept
.data
, {
64 'Authorization': authorization_header_string
66 forever
: constants
.FOREVER_ON
,
67 rejectUnauthorized
: constants
.REJECT_UNAUTHORIZED
,
68 resolveWithFullResponse
: true
73 headers
: _
.extend({}, constants
.HTTP_HEADERS
.accept
.collection
, {
74 'Authorization': authorization_header_string
76 forever
: constants
.FOREVER_ON
,
77 rejectUnauthorized
: constants
.REJECT_UNAUTHORIZED
,
78 resolveWithFullResponse
: true
81 ]).then(function(results
) {
82 // results[0].statusCode => 200/201
83 // results[1].body.collection['rw-project:project'] => List of projects OR 204 with no content
84 if (results
[0].statusCode
!= constants
.HTTP_RESPONSE_CODES
.SUCCESS
.OK
) {
85 var errorMsg
= 'Invalid credentials provided!';
86 logAndRedirectToLogin(errorMsg
, res
, req
);
90 var username
= req
.body
['username'];
91 var project_list_for_user
= [];
93 if (results
[1].statusCode
== constants
.HTTP_RESPONSE_CODES
.SUCCESS
.NO_CONTENT
) {
94 console
.log('No projects added or user ', username
,' not privileged to view projects.');
96 // go through projects and get list of projects that this user belongs to.
97 // pick first one as default project?
99 var projects
= JSON
.parse(results
[1].body
).collection
['rw-project:project'];
100 projects
&& projects
.map(function(project
) {
101 project
['project-config'] &&
102 project
['project-config']['user'] &&
103 project
['project-config']['user'].map(function(user
) {
104 if (user
['user-name'] == username
) {
105 project_list_for_user
.push(project
.name
);
110 req
.session
.projectId
= (project_list_for_user
.length
> 0) && project_list_for_user
.sort() && project_list_for_user
[0];
113 req
.session
.authorization
= authorization_header_string
;
114 req
.session
.loggedIn
= true;
115 req
.session
.userdata
= {
117 // project: req.session.projectId
119 var successMsg
= 'User =>' + username
+ ' successfully logged in.';
120 successMsg
+= req
.session
.projectId
? 'Project =>' + req
.session
.projectId
+ ' set as default.' : '';
122 console
.log(successMsg
);
125 statusCode
: constants
.HTTP_RESPONSE_CODES
.SUCCESS
.CREATED
,
126 data
: JSON
.stringify({
132 }).catch(function(error
) {
133 // Something went wrong - Redirect to /login
134 var errorMsg
= 'Error logging in or getting list of projects. Error: ' + error
;
135 console
.log(errorMsg
);
136 logAndRedirectToLogin(errorMsg
, res
, req
);
141 sessionsAPI
.addProjectToSession = function(req
, res
) {
142 return new Promise(function(resolve
, reject
) {
143 if (req
.session
&& req
.session
.loggedIn
== true) {
144 req
.session
.projectId
= req
.params
.projectId
;
145 var successMsg
= 'Added project' + req
.session
.projectId
+ ' to session' + req
.sessionID
;
146 console
.log(successMsg
);
149 statusCode
: constants
.HTTP_RESPONSE_CODES
.SUCCESS
.OK
,
150 data
: JSON
.stringify({
156 var errorMsg
= 'Session does not exist or not logged in';
157 logAndReject(errorMsg
, reject
);
161 sessionsAPI
.delete = function(req
, res
) {
162 var api_server
= req
.query
["api_server"];
163 var uri
= utils
.confdPort(api_server
);
164 var url
= uri
+ '/api/logout';
165 return new Promise(function(resolve
, reject
) {
170 headers
: _
.extend({}, constants
.HTTP_HEADERS
.accept
.data
, {
171 'Authorization': req
.session
.authorization
173 forever
: constants
.FOREVER_ON
,
174 rejectUnauthorized
: constants
.REJECT_UNAUTHORIZED
,
175 resolveWithFullResponse
: true
177 new Promise(function(success
, failure
) {
178 req
.session
.destroy(function(err
) {
180 var errorMsg
= 'Error deleting session. Error: ' + err
;
181 console
.log(errorMsg
);
188 var successMsg
= 'Success deleting session';
189 console
.log(successMsg
);
197 ]).then(function(result
) {
198 // assume the session was deleted!
199 var message
= 'Session was deleted.'
200 logAndRedirectToLogin(message
, res
, req
);
202 }).catch(function(error
) {
203 var message
= 'Error deleting session or logging out. Error:' + error
;
204 logAndRedirectToLogin(message
, res
, req
);
210 module
.exports
= sessionsAPI
;