NOTICKET - Cleanup
[osm/UI.git] / skyquake / framework / core / modules / api / sessions.js
1 /*
2 *
3 * Copyright 2016 RIFT.IO Inc
4 *
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
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
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.
16 *
17 */
18
19 /**
20 * sessions api module. Provides API functions for sessions
21 * @module framework/core/modules/api/sessions
22 * @author Kiran Kashalkar <kiran.kashalkar@riftio.com>
23 */
24
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');
30 var sessionsAPI = {};
31 var _ = require('lodash');
32 var base64 = require('base-64');
33 var APIVersion = '/v2';
34 var configurationAPI = require('./configuration');
35
36 function logAndReject(mesg, reject) {
37 res.errorMessage = {
38 error: mesg
39 }
40 console.log(mesg);
41 reject(res);
42 }
43
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);
47 console.log(mesg);
48 res.redirect('login.html?api_server=' + api_server + '&upload_server=' + upload_server);
49 res.end();
50 }
51
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) {
59 Promise.all([
60 rp({
61 url: login_url,
62 method: 'POST',
63 headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
64 'Authorization': authorization_header_string
65 }),
66 forever: constants.FOREVER_ON,
67 rejectUnauthorized: constants.REJECT_UNAUTHORIZED,
68 resolveWithFullResponse: true
69 }),
70 rp({
71 url: project_url,
72 method: 'GET',
73 headers: _.extend({}, constants.HTTP_HEADERS.accept.collection, {
74 'Authorization': authorization_header_string
75 }),
76 forever: constants.FOREVER_ON,
77 rejectUnauthorized: constants.REJECT_UNAUTHORIZED,
78 resolveWithFullResponse: true
79 })
80
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);
87 return;
88 }
89
90 var username = req.body['username'];
91 var project_list_for_user = [];
92
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.');
95 } else {
96 // go through projects and get list of projects that this user belongs to.
97 // pick first one as default project?
98
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);
106 }
107 });
108 });
109
110 req.session.projectId = (project_list_for_user.length > 0) && project_list_for_user.sort() && project_list_for_user[0];
111 }
112
113 req.session.authorization = authorization_header_string;
114 req.session.loggedIn = true;
115
116 var successMsg = 'User =>' + username + ' successfully logged in.';
117 successMsg += req.session.projectId ? 'Project =>' + req.session.projectId + ' set as default.' : '';
118
119 console.log(successMsg);
120
121 var response = {
122 statusCode: constants.HTTP_RESPONSE_CODES.SUCCESS.CREATED,
123 data: JSON.stringify({
124 status: successMsg
125 })
126 };
127 resolve(response);
128
129 }).catch(function(error) {
130 // Something went wrong - Redirect to /login
131 var errorMsg = 'Error logging in or getting list of projects. Error: ' + error;
132 console.log(errorMsg);
133 logAndRedirectToLogin(errorMsg, res, req);
134 });
135 })
136 };
137
138 sessionsAPI.addProjectToSession = function(req, res) {
139 return new Promise(function(resolve, reject) {
140 if (req.session && req.session.loggedIn == true) {
141 req.session.projectId = req.params.projectId;
142 var successMsg = 'Added project' + projectId + ' to session' + req.sessionID;
143 console.log(successMsg);
144
145 return resolve ({
146 statusCode: constants.HTTP_RESPONSE_CODES.SUCCESS.OK,
147 data: JSON.stringify({
148 status: successMsg
149 })
150 });
151 }
152
153 var errorMsg = 'Session does not exist or not logged in';
154 logAndReject(errorMsg, reject);
155 });
156 }
157
158 sessionsAPI.delete = function(req, res) {
159 var api_server = req.query["api_server"];
160 var uri = utils.confdPort(api_server);
161 var url = uri + '/api/logout';
162 return new Promise(function(resolve, reject) {
163 Promise.all([
164 rp({
165 url: url,
166 method: 'POST',
167 headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
168 'Authorization': req.session.authorization
169 }),
170 forever: constants.FOREVER_ON,
171 rejectUnauthorized: constants.REJECT_UNAUTHORIZED,
172 resolveWithFullResponse: true
173 }),
174 new Promise(function(success, failure) {
175 req.session.destroy(function(err) {
176 if (err) {
177 var errorMsg = 'Error deleting session. Error: ' + err;
178 console.log(errorMsg);
179 success({
180 status: 'error',
181 message: errorMsg
182 });
183 }
184
185 var successMsg = 'Success deleting session';
186 console.log(successMsg);
187
188 success({
189 status: 'success',
190 message: successMsg
191 });
192 });
193 })
194 ]).then(function(result) {
195 // assume the session was deleted!
196 var message = 'Session was deleted.'
197 logAndRedirectToLogin(message, res, req);
198
199 }).catch(function(error) {
200 var message = 'Error deleting session or logging out. Error:' + error;
201 logAndRedirectToLogin(message, res, req);
202 });
203 });
204 }
205
206
207 module.exports = sessionsAPI;