Commit 687dfc70 authored by Alina Habibulina's avatar Alina Habibulina

+ SynergyUser class

parent 7a6e7447
package kz.arta.ext.sap.db; package kz.arta.ext.sap.db;
import kz.arta.ext.sap.service.SynergyUser;
import kz.arta.ext.sap.util.ConnectionPool; import kz.arta.ext.sap.util.ConnectionPool;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -21,48 +22,19 @@ import java.sql.ResultSet; ...@@ -21,48 +22,19 @@ import java.sql.ResultSet;
**/ **/
public class UserManager { public class UserManager {
private static final Logger LOGGER = LoggerFactory.getLogger(UserManager.class); private static final Logger LOGGER = LoggerFactory.getLogger(UserManager.class);
private static final String IS_ADMIN = "isadmin";
private static final String IS_AUTH = "isauth";
public static int ifUserExist(String login) { /**
Connection con = null; *
ResultSet res = null; * @param login Логин пользователя, которому требуется сменить/установить пароль
PreparedStatement chechExistance = null; * @param new_pass Новый пароль
try { * @return Возвращает 200 - в случае успешной смены пароля, 500 - в случае возникновения каких-либо ошибок с базой данных.
con = ConnectionPool.getConnection(); */
chechExistance = con.prepareStatement("SELECT * FROM users WHERE login = ? ");
chechExistance.setString(1, login);
res = chechExistance.executeQuery();
if(res.next()) {
return 200;
}
else return 404;
} catch (SQLException | NamingException e) {
LOGGER.error("", e);
return 500;
} finally {
if (res != null) {
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (chechExistance != null) {
try {
chechExistance.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
ConnectionPool.close(con);
}
}
public static int setPass(String login, String new_pass) { public static int setPass(String login, String new_pass) {
if(UserManager.ifUserExist(login) == 200) { if(UserManager.dbInteraction(login, null, "isExist").getisExist()) {
Connection con = null; Connection con = null;
PreparedStatement updatePassword = null; PreparedStatement updatePassword = null;
...@@ -91,64 +63,52 @@ public class UserManager { ...@@ -91,64 +63,52 @@ public class UserManager {
} else return 404; } else return 404;
} }
public static int checkAuth(String login, String password) { /**
*
* @param login Логин пользователя
* @param field Поле для поиска записей в базе
* @param value Значение, по которому нужно искать
* @param requestType Может принимать значения "isadmin", "isauth", или любое другое для проверки существования пользователя;
* @return Объект класса SynergyUser
*/
public static SynergyUser dbInteraction(String login, String value, String requestType) {
Connection con = null; Connection con = null;
PreparedStatement searchUser = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
SynergyUser user = new SynergyUser();
try { try {
con = ConnectionPool.getConnection(); con = ConnectionPool.getConnection();
searchUser = con.prepareStatement("SELECT * FROM users WHERE login = ? AND password = md5(?)");
searchUser.setString(1, login);
searchUser.setString(2, password);
rs = searchUser.executeQuery();
if(rs.next()) { if(requestType.equals(IS_AUTH)) {
return 200; ps = con.prepareStatement("SELECT * FROM users WHERE login = ? AND password = md5( ? )");
} ps.setString(2, value);
} else if(requestType.equals(IS_ADMIN)){
ps = con.prepareStatement("SELECT * FROM users WHERE login = ? AND isadmin = 1");
} else ps = con.prepareStatement("SELECT * FROM users WHERE login = ? ");
return 401; ps.setString(1, login);
} catch (SQLException | NamingException e) { rs = ps.executeQuery();
LOGGER.error("", e);
return 500;
} finally {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
LOGGER.error("", e);
}
}
if(searchUser != null) {
try {
searchUser.close();
} catch (SQLException e) {
LOGGER.error("", e);
}
}
ConnectionPool.close(con);
}
}
public static int isAdmin(String login) {
Connection con = null;
PreparedStatement isAdminCheck = null;
ResultSet rs = null;
try {
con = ConnectionPool.getConnection();
isAdminCheck = con.prepareStatement("SELECT * FROM users WHERE login = ? AND isadmin = 1");
isAdminCheck.setString(1, login);
rs = isAdminCheck.executeQuery();
if(rs.next()) { if(rs.next()) {
return 1; if(requestType.equals(IS_AUTH)){
user.setIsAuth(true);
} else if(requestType.equals(IS_ADMIN)) {
user.setIsAdmin(true);
user.setIsAuth(true);
} else {
user.setExist(true);
}
} }
return 0; return user;
} catch (SQLException | NamingException e) { } catch (SQLException | NamingException e) {
LOGGER.error("", e); LOGGER.error("", e);
return 500; user.setIsError(500);
return user;
} finally { } finally {
if(rs != null) { if(rs != null) {
try { try {
...@@ -157,14 +117,30 @@ public class UserManager { ...@@ -157,14 +117,30 @@ public class UserManager {
LOGGER.error("", e); LOGGER.error("", e);
} }
} }
if(isAdminCheck != null) { if(ps != null) {
try { try {
isAdminCheck.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.error("", e); LOGGER.error("", e);
} }
} }
ConnectionPool.close(con); ConnectionPool.close(con);
} }
} }
} }
...@@ -33,24 +33,31 @@ public class PasswordSetService { ...@@ -33,24 +33,31 @@ public class PasswordSetService {
return "{\"status\":\"working\"}"; return "{\"status\":\"working\"}";
} }
/**
*
* @param authParam header Параметр авторизации Basic Auth
* @param currentUserLogin Логин пользователя, который делает запрос
* @param login Логин пользователя, которому нужно поменять/установить пароль
* @param new_pass Новыйй пароль
*
*/
@POST @POST
@Path("/set_password") @Path("/set_password")
@Produces(MediaType.APPLICATION_JSON + "; charset=utf-8") @Produces(MediaType.APPLICATION_JSON + "; charset=utf-8")
public String setPassword(@HeaderParam("authorization") String authParam, @QueryParam("currentUserLogin") String currentUserLogin, @QueryParam("login") String login, @QueryParam("new_password") String new_pass){ public String setPassword(@HeaderParam("authorization") String authParam, @QueryParam("currentUserLogin") String currentUserLogin, @QueryParam("login") String login, @QueryParam("new_password") String new_pass){
try { try {
boolean su = UserManager.dbInteraction(currentUserLogin, null, "isadmin").getIsAdmin();
int isAdminResult = UserManager.isAdmin(currentUserLogin); if (su) {
if (isAdminResult == 1) {
return PasswordSetService.errorMessagesHandler(UserManager.setPass(login, new_pass)); return PasswordSetService.errorMessagesHandler(UserManager.setPass(login, new_pass));
} else if (isAdminResult == 0){ } else {
if( login.equals(currentUserLogin)) return PasswordSetService.errorMessagesHandler(UserManager.setPass(login, new_pass)); if( login.equals(currentUserLogin)) return PasswordSetService.errorMessagesHandler(UserManager.setPass(login, new_pass));
else return PasswordSetService.errorMessagesHandler(403); else return PasswordSetService.errorMessagesHandler(403);
} else {
return PasswordSetService.errorMessagesHandler(500);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
......
...@@ -36,6 +36,7 @@ public class SecurityInterceptor implements PreProcessInterceptor { ...@@ -36,6 +36,7 @@ public class SecurityInterceptor implements PreProcessInterceptor {
private static final ServerResponse ACCESS_DENIED = new ServerResponse("{\"status\":\"401 Unauthorized!\", \"errorCode\": \"401\"}", 401, new Headers<Object>()); private static final ServerResponse ACCESS_DENIED = new ServerResponse("{\"status\":\"401 Unauthorized!\", \"errorCode\": \"401\"}", 401, new Headers<Object>());
private static final ServerResponse DB_ERROR = new ServerResponse("{\"status\":\"Something has gone wrong on serve/db\", \"errorCode\": \"500\"}", 500, new Headers<Object>()); private static final ServerResponse DB_ERROR = new ServerResponse("{\"status\":\"Something has gone wrong on serve/db\", \"errorCode\": \"500\"}", 500, new Headers<Object>());
private static final String AUTHORIZATION = "Authorization";
@Context @Context
...@@ -46,10 +47,9 @@ public class SecurityInterceptor implements PreProcessInterceptor { ...@@ -46,10 +47,9 @@ public class SecurityInterceptor implements PreProcessInterceptor {
@Override @Override
public ServerResponse preProcess(HttpRequest httpRequest, ResourceMethod resourceMethod) throws Failure, WebApplicationException { public ServerResponse preProcess(HttpRequest httpRequest, ResourceMethod resourceMethod) throws Failure, WebApplicationException {
String currentUserLogin = null;
if (httpRequest.getUri().getPath().startsWith("/uservice/")){ if (httpRequest.getUri().getPath().startsWith("/uservice/")){
String authParam = request.getHeader("Authorization"); String authParam = request.getHeader(AUTHORIZATION);
String decodedAuth = ""; String decodedAuth = "";
String[] authParts = authParam.split(" "); String[] authParts = authParam.split(" ");
...@@ -65,14 +65,15 @@ public class SecurityInterceptor implements PreProcessInterceptor { ...@@ -65,14 +65,15 @@ public class SecurityInterceptor implements PreProcessInterceptor {
String[] authArray = decodedAuth.split(":"); String[] authArray = decodedAuth.split(":");
currentUserLogin = authArray[0]; String currentUserLogin = authArray[0];
String currentUserPass = authArray[1]; String currentUserPass = authArray[1];
int authResult = UserManager.checkAuth(currentUserLogin, currentUserPass); SynergyUser su = UserManager.dbInteraction(currentUserLogin, currentUserPass, "isauth");
if (authResult == 401){
return ACCESS_DENIED; if (su.getIsError() == 500) {
} else if (authResult == 500){
return DB_ERROR; return DB_ERROR;
} else if (!su.getIsAuth()){
return ACCESS_DENIED;
} }
httpRequest.getUri().getQueryParameters().add("currentUserLogin", currentUserLogin); httpRequest.getUri().getQueryParameters().add("currentUserLogin", currentUserLogin);
......
package kz.arta.ext.sap.service;
public class SynergyUser {
private boolean isAdmin;
private boolean isAuth;
private boolean isExist;
private int isError;
public SynergyUser() {
this.isAdmin = false;
this.isAuth = false;
this.isExist = false;
this.isError = 0;
}
public boolean getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
public boolean getIsAuth() {
return isAuth;
}
public void setIsAuth(boolean isAuth) {
this.isAuth = isAuth;
}
public int getIsError() {
return isError;
}
public void setIsError(int isError) {
this.isError = isError;
}
public boolean getisExist() {
return isExist;
}
public void setExist(boolean isExist) {
this.isExist = isExist;
}
}
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