Skip to content
Snippets Groups Projects
Commit 13c9d2ed authored by Bart Chou's avatar Bart Chou
Browse files

now server can create login cookie and client can store cookie in broser. We...

now server can create login cookie and client can store cookie in broser. We use userId as token for login cookie for convinence for now.
parent 48d2fa2c
No related branches found
No related tags found
3 merge requests!34Sprint 2 done,!311. add vuex,!29now server can create login cookie and client can store cookie in broser. We use userId as token for login cookie for convinence for now.
......@@ -9,15 +9,19 @@ import vt.CS5934.SwitchRoom.models.ResponseModel;
import vt.CS5934.SwitchRoom.models.UserModel;
import vt.CS5934.SwitchRoom.services.UserService;
import vt.CS5934.SwitchRoom.hash.SHAModel;
import lombok.Getter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.security.NoSuchAlgorithmException;
/**
* The "@RestController" made the class into rest handle class
* The "@RequestMapping("example")" on the class level make it only react to url ".../example/..."
*/
@CrossOrigin
@CrossOrigin(
allowCredentials = "true",
origins = {"http://localhost:8080/"}
)
@RestController
@RequestMapping("user")
public class UserController {
......@@ -58,7 +62,7 @@ public class UserController {
}
@PostMapping("/loginUser")
public ResponseModel loginUser(@RequestBody UserModel user) throws NoSuchAlgorithmException {
public ResponseModel loginUser(@RequestBody UserModel user, HttpServletResponse servletResponse) throws NoSuchAlgorithmException {
logger.info("You reached the handlePost() functions.");
ResponseModel response = new ResponseModel();
SHAModel hash = new SHAModel();
......@@ -69,16 +73,23 @@ public class UserController {
if (existUser != null && existUser.getPassword().equals(inputPassword)) {
response.setMessage("Login in successfully");
response.setStatus(HttpStatus.OK);
var token = Token.of(existUser.getUserId(), 10L, "secret");
existUser.setToken(token.getToken());
// var token = Token.of(existUser.getUserId(), 10L, "secret");
// existUser.setToken(token.getToken());
} else {
response.setMessage("Couldn't find an account matching the login info you entered");
response.setStatus(HttpStatus.FORBIDDEN);
}
// Cookie theCookie = new Cookie("token", token.getToken());
Cookie theCookie = new Cookie("userId", Integer.toString(existUser.getUserId())); // use UserId for now
theCookie.setHttpOnly(false);
theCookie.setSecure(false);
theCookie.setPath("/");
theCookie.setMaxAge(60);
servletResponse.addCookie(theCookie);
existUser.setPassword(null);
response.setData(existUser);
response.setData(existUser);
return response;
}catch (Exception e){
......@@ -88,10 +99,17 @@ public class UserController {
null);
}
}
@PostMapping("/checkLoginSession")
public ResponseModel checkLoginSession(@RequestBody Object json) {
@GetMapping("/checkLoginSession")
public ResponseModel checkLoginSession(@CookieValue(value = "userId", required = false) String token) {
ResponseModel response = new ResponseModel();
response.setStatus(HttpStatus.OK);
if (token == null) {
System.out.println("checkLoginSession: FORBIDDEN");
response.setStatus(HttpStatus.FORBIDDEN);
} else {
System.out.println("checkLoginSession: OK");
response.setStatus(HttpStatus.OK);
}
return response;
}
......
......@@ -30,8 +30,8 @@ export default defineComponent({
logOut: "logOutApi",
}),
hanldeLogOut() {
localStorage.setItem("token", "");
this.logOut()
document.cookie = 'userId=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
this.$router.push("/");
}
}
......
......@@ -85,15 +85,14 @@ export default defineComponent({
actionLoginApi: "loginApi",
}),
async handleCreated() {
let token = localStorage.getItem('token');
if (token) {
await checkLoginSession(JSON.stringify(token))
.then((result) => {
if (result.status == "OK") {
this.$router.push("/login-main-page");
}
})
}
await checkLoginSession()
.then((result) => {
if (result.status == "OK") {
this.$router.push({name: 'LoginMainPage'});
} else {
this.$router.push({name: 'home'})
}
})
},
async handleLogin() {
const payload = {
......@@ -102,7 +101,7 @@ export default defineComponent({
};
await this.actionLoginApi(payload);
if (this.getLoginStatus){
this.$router.push("/login-main-page");
this.$router.push({name: 'LoginMainPage'});
}
},
},
......
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import HomeView from "../views/HomeView.vue";
import RegisterView from "../views/RegisterView.vue";
import store from "../store/index"
const routes: Array<RouteRecordRaw> = [
{
......@@ -50,7 +49,7 @@ const router = createRouter({
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters["auth/getLoginStatus"]) {
if (!document.cookie) {
next({ name: 'home' })
} else {
next()
......
......@@ -11,6 +11,7 @@ function Get(path: string) {
return fetch(url, {
method: "GET",
credentials: "include",
})
.then((response) => {
if (response.ok) {
......@@ -31,6 +32,7 @@ function Post(path: string, bodyData: any) {
console.log("With Data: ", JSON.stringify(bodyData));
return fetch(url, {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
......
......@@ -11,9 +11,9 @@ function loginUser(userData: any) {
// console.log(Server_URL + baseUrl + urlPath);
return serverHttpService.Post(baseUrl + urlPath, JSON.parse(userData));
}
function checkLoginSession(token: any) {
function checkLoginSession() {
const urlPath = "/checkLoginSession";
return serverHttpService.Post(baseUrl + urlPath, JSON.parse(token));
return serverHttpService.Get(baseUrl + urlPath);
}
export { postUserDataToServer, loginUser, checkLoginSession };
......@@ -16,8 +16,6 @@ const actions = {
.catch((error) => alert(error));
if (response.status == "OK") {
commit("setLoginStatus", true);
console.log("login token: " + response.data.token)
localStorage.setItem('token', response.data.token)
} else {
alert(response.message)
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment