Commit 8bb34112 authored by Piotr Gawron's avatar Piotr Gawron
Browse files

login/logout api in new location

parent 1c4b2f21
......@@ -180,19 +180,25 @@ ServerConnector.sendPatchRequest = function(url, params) {
});
};
ServerConnector.getToken = function() {
ServerConnector.getToken = function(token) {
if (token !== undefined) {
return Promise.resolve(token);
}
var self = this;
var token = self.getSessionData(null).getToken();
token = self.getSessionData(null).getToken();
if (token === undefined) {
return self.login();
} else {
// if the project is not initialized then check if we can download data
// using current token
if (self.getSessionData().getProject() === null) {
return self.isValidToken(token).then(function(isOk) {
if (isOk) {
return token;
} else {
return self.login();
}
return self.getConfiguration({
token : token
}).then(function() {
return token;
}, function() {
return self.login();
});
} else {
return Promise.resolve(token);
......@@ -297,8 +303,7 @@ ServerConnector.getReferenceGenomeUrl = function(queryParams, filterParams) {
ServerConnector.loginUrl = function() {
return this.getApiUrl({
type : "user",
method : "login"
type : "/doLogin",
});
};
......@@ -566,36 +571,21 @@ ServerConnector.getProjectSourceUrl = function(params) {
});
};
ServerConnector.getUserUrl = function(params) {
var userId = params.userId;
var token = params.token;
ServerConnector.getUserUrl = function(queryParams, filterParams) {
return this.getApiUrl({
type : "user",
method : "getUser",
params : {
userId : userId,
token : token,
},
});
};
ServerConnector.isValidTokenUrl = function(params) {
var token = params.token;
return this.getApiUrl({
type : "user",
method : "tokenStatus",
params : {
token : token,
},
type : "users/",
method : queryParams.login,
params : filterParams,
});
};
ServerConnector.getConfiguration = function() {
ServerConnector.getConfiguration = function(params) {
if (params === undefined) {
params = {};
}
var self = this;
if (this._configuration === undefined) {
return self.getToken().then(function(token) {
return self.getToken(params.token).then(function(token) {
return self.readFile(self.getConfigurationUrl(null, {
token : token
}));
......@@ -640,20 +630,23 @@ ServerConnector.getLoggedUser = function() {
if (self._loggedUser !== undefined) {
return Promise.resolve(self._loggedUser);
} else {
return self.getUser().then(function(user) {
return self.getUser(self.getSessionData().getLogin()).then(function(user) {
self._loggedUser = user;
return self._loggedUser;
});
}
};
ServerConnector.getUser = function(userId) {
ServerConnector.getUser = function(login) {
var self = this;
var queryParams = {
login : login,
};
var filterParams = {};
return self.getToken().then(function(token) {
return self.readFile(self.getUserUrl({
token : token,
userId : userId
}));
filterParams.token = token;
return self.readFile(self.getUserUrl(queryParams, filterParams));
}).then(function(content) {
var obj = JSON.parse(content);
return new User(obj);
......@@ -919,28 +912,16 @@ ServerConnector.login = function(login, password) {
return Promise.reject(obj.error);
} else {
self.getSessionData().setToken(token);
self.getSessionData().setLogin(params.login);
return Promise.resolve(token);
}
});
};
ServerConnector.isValidToken = function(token) {
var self = this;
return new Promise(function(resolve) {
return self.readFile(self.isValidTokenUrl({
token : token
})).then(function(content) {
var obj = JSON.parse(content);
resolve(obj.error === undefined);
}, function() {
resolve(false);
});
});
};
ServerConnector.logout = function() {
var self = this;
self.getSessionData().setToken(undefined);
self.getSessionData().setLogin(undefined);
return Promise.resolve();
};
......
......@@ -16,6 +16,7 @@ var ServerConnectorMock = OriginalServerConnector;
ServerConnectorMock.init = function() {
this._customMap = null;
this._sessionData = undefined;
this._configuration = undefined;
// add listener types
};
......
......@@ -3,6 +3,7 @@
require("./mocha-config.js");
var Alias = require('../../main/js/map/data/Alias');
var Configuration = require('../../main/js/Configuration');
var LayoutAlias = require('../../main/js/map/data/LayoutAlias');
var Project = require('../../main/js/map/data/Project');
var Reaction = require('../../main/js/map/data/Reaction');
......@@ -143,6 +144,12 @@ describe('ServerConnector', function() {
});
});
it('getConfiguration', function() {
return ServerConnector.getConfiguration().then(function(configuration) {
assert.ok(configuration instanceof Configuration);
});
});
});
......@@ -10,7 +10,7 @@ global.navigator = {
userAgent : 'node.js',
appName : 'MinervaUnitTest',
appVersion : '0.0.1',
};
var jsdom = require('jsdom');
......@@ -91,6 +91,7 @@ beforeEach(function() {
ServerConnector.init();
ServerConnector.getSessionData(null).setToken("MOCK_TOKEN_ID");
ServerConnector.getSessionData(null).setLogin("anonymous");
GuiConnector.init();
......
{"id":"MOCK_TOKEN_ID","expires":{"year":3017,"month":0,"dayOfMonth":30,"hourOfDay":18,"minute":34,"second":13}}
\ No newline at end of file
......@@ -22,8 +22,7 @@ public abstract class BaseController {
@ExceptionHandler({ Exception.class })
public ResponseEntity<Object> handleException(Exception e, WebRequest request) {
logger.error(e, e);
if (e instanceof SecurityException) {
if (e instanceof lcsb.mapviewer.services.SecurityException) {
return new ResponseEntity<Object>("{\"error\" : \"Access denied.\",\"reason\":\"" + e.getMessage() + "\"}", new HttpHeaders(), HttpStatus.FORBIDDEN);
} else if (e instanceof ObjectNotFoundException) {
return new ResponseEntity<Object>("{\"error\" : \"Object not found.\",\"reason\":\"" + e.getMessage() + "\"}", new HttpHeaders(), HttpStatus.NOT_FOUND);
......@@ -31,6 +30,7 @@ public abstract class BaseController {
return new ResponseEntity<Object>(
"{\"error\" : \"Query server error.\",\"reason\":\"" + e.getMessage() + "\"}", new HttpHeaders(), HttpStatus.BAD_REQUEST);
} else {
logger.error(e, e);
return new ResponseEntity<Object>(
"{\"error\" : \"Internal server error.\",\"reason\":\"" + e.getMessage() + "\"}", new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
......
......@@ -31,6 +31,7 @@ public class ConfigurationRestImpl {
private IConfigurationService configurationService;
public List<ConfigurationView> getAllValues(@RequestParam(value = "token") String token) throws SecurityException {
userService.getToken(token);
return configurationService.getAllValues();
}
......@@ -68,7 +69,8 @@ public class ConfigurationRestImpl {
this.configurationService = configurationService;
}
public List<Map<String, Object>> getImageFormats(String token) {
public List<Map<String, Object>> getImageFormats(String token) throws SecurityException {
userService.getToken(token);
List<Map<String, Object>> result = new ArrayList<>();
List<Pair<String, Class<? extends AbstractImageGenerator>>> imageGenerators = new ImageGenerators().getAvailableImageGenerators();
......@@ -82,7 +84,8 @@ public class ConfigurationRestImpl {
return result;
}
public List<Map<String, Object>> getModelFormats(String token) {
public List<Map<String, Object>> getModelFormats(String token) throws SecurityException {
userService.getToken(token);
List<IConverter> converters = new ArrayList<>();
converters.add(new CellDesignerXmlParser());
converters.add(new SbgnmlXmlConverter());
......@@ -98,7 +101,8 @@ public class ConfigurationRestImpl {
return result;
}
public List<Map<String, Object>> getOverlayTypes(String token) {
public List<Map<String, Object>> getOverlayTypes(String token) throws SecurityException {
userService.getToken(token);
List<Map<String, Object>> result = new ArrayList<>();
for (ColorSchemaType type : ColorSchemaType.values()) {
Map<String, Object> map = new HashMap<>();
......
package lcsb.mapviewer.api.controller;
package lcsb.mapviewer.api.users;
import java.util.HashMap;
import java.util.Map;
......@@ -6,19 +6,20 @@ import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import lcsb.mapviewer.api.BaseController;
import lcsb.mapviewer.api.ObjectNotFoundException;
import lcsb.mapviewer.common.Configuration;
import lcsb.mapviewer.services.SecurityException;
import lcsb.mapviewer.services.interfaces.IUserService;
import lcsb.mapviewer.services.view.AuthenticationToken;
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
Logger logger = Logger.getLogger(UserController.class);
......@@ -28,33 +29,31 @@ public class UserController extends BaseController {
@Autowired
private UserRestImpl userRest;
@RequestMapping(value = "/login", method = { RequestMethod.GET, RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
public Map<String, Object> login(@RequestParam(value = "login", defaultValue = Configuration.ANONYMOUS_LOGIN) String login,
@RequestParam(value = "password", required = false) String password) {
@RequestMapping(value = "/doLogin", method = { RequestMethod.GET, RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
public Map<String, Object> login(//
@RequestParam(value = "login", defaultValue = Configuration.ANONYMOUS_LOGIN) String login, //
@RequestParam(value = "password", required = false) String password//
) throws SecurityException {
AuthenticationToken token = userService.login(login, password);
Map<String, Object> result = new HashMap<>();
if (token == null) {
result.put("error", "Invalid credentials");
throw new SecurityException("Invalid credentials");
} else {
result.put("id", token.getId());
result.put("expires", token.getExpires());
}
return result;
}
@RequestMapping(value = "/tokenStatus", method = { RequestMethod.GET, RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
public AuthenticationToken tokenSatus(@RequestParam(value = "token", required = false) String token) throws SecurityException {
return userService.getToken(token);
@RequestMapping(value = "/users/{login}", method = { RequestMethod.GET, RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
public Map<String, Object> getUser(//
@RequestParam(value = "token", required = false) String token, //
@PathVariable(value = "login") String login, //
@RequestParam(value = "columns", defaultValue = "") String columns//
) throws SecurityException, ObjectNotFoundException {
return userRest.getUser(token, login, columns);
}
@RequestMapping(value = "/getUser", method = { RequestMethod.GET, RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
public Map<String, Object> getUser(@RequestParam(value = "token", required = false) String token,
@RequestParam(value = "userId", defaultValue = "") String userId, @RequestParam(value = "columns", defaultValue = "") String columns)
throws SecurityException {
return userRest.getUser(token, userId, columns);
}
@RequestMapping(value = "/logout", method = { RequestMethod.GET, RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
@RequestMapping(value = "/doLogout", method = { RequestMethod.GET, RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
public Map<String, String> logout(@RequestParam(value = "token", required = false) String token) throws SecurityException {
userService.logout(token);
Map<String, String> response = new HashMap<>();
......
package lcsb.mapviewer.api.controller;
package lcsb.mapviewer.api.users;
import java.util.ArrayList;
import java.util.HashMap;
......@@ -10,6 +10,7 @@ import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import lcsb.mapviewer.api.ObjectNotFoundException;
import lcsb.mapviewer.common.exception.InvalidArgumentException;
import lcsb.mapviewer.model.user.BasicPrivilege;
import lcsb.mapviewer.model.user.ObjectPrivilege;
......@@ -45,25 +46,19 @@ public class UserRestImpl {
this.userService = userService;
}
public Map<String, Object> getUser(String token, String userId, String columns) throws SecurityException {
public Map<String, Object> getUser(String token, String login, String columns) throws SecurityException, ObjectNotFoundException {
User ownUserData = userService.getUserByToken(token);
Integer id = null;
if (userId != null && !userId.isEmpty()) {
id = Integer.valueOf(userId);
} else {
id = ownUserData.getId();
}
Set<String> columnSet = createUserColumnSet(columns);
boolean isAdmin = userService.userHasPrivilege(ownUserData, PrivilegeType.USER_MANAGEMENT);
if (ownUserData.getId().equals(id)) {
if (ownUserData.getLogin().equals(login)) {
return prepareUse(ownUserData, columnSet, true);
} else if (isAdmin) {
User user = userService.getUserById(id);
User user = userService.getUserByLogin(login);
if (user == null) {
throw new SecurityException("You cannot access data of the user with given id");
throw new ObjectNotFoundException("User doesn't exist");
}
return prepareUse(user, columnSet, isAdmin);
} else {
......
......@@ -25,6 +25,6 @@
<bean id="ReactionsRestImpl" class="lcsb.mapviewer.api.projects.models.bioEntities.reactions.ReactionsRestImpl"/>
<bean id="ReferenceGenomeRestImpl" class="lcsb.mapviewer.api.genomics.ReferenceGenomeRestImpl"/>
<bean id="UserRestImpl" class="lcsb.mapviewer.api.controller.UserRestImpl"/>
<bean id="UserRestImpl" class="lcsb.mapviewer.api.users.UserRestImpl"/>
</beans>
\ No newline at end of file
......@@ -6,9 +6,9 @@ import org.junit.runners.Suite.SuiteClasses;
import lcsb.mapviewer.api.comment.AllCommentTests;
import lcsb.mapviewer.api.configuration.AllConfigurationTests;
import lcsb.mapviewer.api.controller.AllUserTests;
import lcsb.mapviewer.api.genomics.AllGenomicsTests;
import lcsb.mapviewer.api.projects.AllProjectTests;
import lcsb.mapviewer.api.users.AllUserTests;
@RunWith(Suite.class)
@SuiteClasses({ AllCommentTests.class, //
......
package lcsb.mapviewer.api.controller;
package lcsb.mapviewer.api.users;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
......
package lcsb.mapviewer.api.controller;
package lcsb.mapviewer.api.users;
import static org.junit.Assert.assertNotNull;
......@@ -10,6 +10,7 @@ import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import lcsb.mapviewer.api.RestTestFunctions;
import lcsb.mapviewer.api.users.UserRestImpl;
public class UserRestImplTest extends RestTestFunctions {
Logger logger = Logger.getLogger(UserRestImplTest.class);
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment