83 lines
2.6 KiB
Java
83 lines
2.6 KiB
Java
package net.mindoverflow.webmarker.webserver.controllers;
|
|
|
|
import com.auth0.jwt.JWT;
|
|
import com.auth0.jwt.algorithms.Algorithm;
|
|
import com.google.gson.JsonObject;
|
|
import net.mindoverflow.webmarker.utils.FileUtils;
|
|
import net.mindoverflow.webmarker.utils.config.ConfigEntries;
|
|
import net.mindoverflow.webmarker.utils.messaging.Messenger;
|
|
import net.mindoverflow.webmarker.utils.security.EncryptionUtils;
|
|
import net.mindoverflow.webmarker.utils.security.SafetyCheck;
|
|
import net.mindoverflow.webmarker.utils.sql.MarkerSQLUtils;
|
|
import ro.pippo.controller.Controller;
|
|
import ro.pippo.controller.POST;
|
|
import ro.pippo.controller.Path;
|
|
import ro.pippo.core.route.RouteContext;
|
|
|
|
import java.time.ZonedDateTime;
|
|
import java.util.Date;
|
|
|
|
@Path("/api/v1/login")
|
|
public class LoginController extends Controller
|
|
{
|
|
private final Messenger msg = new Messenger();
|
|
|
|
@POST
|
|
public void login()
|
|
{
|
|
RouteContext routeContext = getRouteContext();
|
|
|
|
|
|
String body = routeContext.getRequest().getBody();
|
|
JsonObject jsonObject = FileUtils.stringToJson(body);
|
|
|
|
String username = jsonObject.get("username").getAsString();
|
|
String encodedPassword = jsonObject.get("password").getAsString();
|
|
String encoding = jsonObject.get("encoding").getAsString();
|
|
|
|
if(!SafetyCheck.isValidEncoding(encoding))
|
|
{
|
|
routeContext.send("Invalid encoding: '" + encoding + "'!");
|
|
return;
|
|
}
|
|
|
|
String password = EncryptionUtils.handleEncoding(encoding, encodedPassword);
|
|
|
|
if(!SafetyCheck.isSafeUsername(username))
|
|
{
|
|
routeContext.send("Invalid username!");
|
|
return;
|
|
}
|
|
|
|
if(!SafetyCheck.isSafePassword(password))
|
|
{
|
|
routeContext.send("Invalid password!");
|
|
return;
|
|
}
|
|
|
|
if(!MarkerSQLUtils.userExists(username))
|
|
{
|
|
routeContext.send("User does not exist!");
|
|
return;
|
|
}
|
|
|
|
String bcryptedStoredPassword = MarkerSQLUtils.getUserBcryptedPassword(username);
|
|
|
|
if(!EncryptionUtils.bcryptMatches(bcryptedStoredPassword, password))
|
|
{
|
|
routeContext.send("Wrong password!");
|
|
return;
|
|
}
|
|
|
|
// JWT
|
|
Algorithm algorithm = Algorithm.HMAC256((String) ConfigEntries.JWT_SECRET.getValue());
|
|
String token = JWT.create()
|
|
.withClaim("username", username)
|
|
.withExpiresAt(Date.from(ZonedDateTime.now().plusMinutes(60).toInstant()))
|
|
.sign(algorithm);
|
|
|
|
routeContext.send(token);
|
|
msg.info("User " + username + " logged in!");
|
|
}
|
|
}
|