Skip to content
Snippets Groups Projects
Commit 571a1081 authored by fz2907's avatar fz2907
Browse files

Merge branch 'LoginPage' into 'sprint_1'

Login page done

See merge request !25
parents ce38666a 14207c79
No related branches found
No related tags found
2 merge requests!27Sprint 1 done,!25Login page done
Showing with 164 additions and 44 deletions
......@@ -8,7 +8,6 @@ import org.springframework.web.bind.annotation.*;
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 java.security.NoSuchAlgorithmException;
......@@ -40,10 +39,9 @@ public class UserController {
public ResponseModel handlePost(@RequestBody UserModel newUser) throws NoSuchAlgorithmException {
logger.info("You reached the handlePost() functions.");
ResponseModel response = new ResponseModel();
SHAModel hash = new SHAModel();
try{
UserModel userModel = userService.addUserToDB(newUser.getUsername(), hash.get_SHA_1_SecurePassword(newUser.getPassword()), newUser.getEmail(), newUser.getFirstname(), newUser.getLastname(), newUser.getGender());
UserModel userModel = userService.addUserToDB(newUser.getUsername(), userService.hashPassword(newUser.getPassword()), newUser.getEmail(), newUser.getFirstname(), newUser.getLastname(), newUser.getGender());
response.setMessage("Saved successfully");
response.setStatus(HttpStatus.OK);
response.setData(userModel);
......@@ -55,4 +53,38 @@ public class UserController {
null);
}
}
@PostMapping("/loginUser")
public ResponseModel loginUser(@RequestBody UserModel user) throws NoSuchAlgorithmException {
logger.info("You reached the handlePost() functions.");
ResponseModel response = new ResponseModel();
String inputPassword = userService.hashPassword(user.getPassword());
// hash.get_SHA_1_SecurePassword(user.getPassword());
try{
UserModel existUser = userService.loginUser(user.getUsername());
if (existUser != null && existUser.getPassword().equals(inputPassword)) {
response.setMessage("Login in successfully");
response.setStatus(HttpStatus.OK);
} else {
response.setMessage("Couldn't find an account matching the login info you entered");
response.setStatus(HttpStatus.FORBIDDEN);
}
existUser.setPassword(null);
response.setData(existUser);
// UserModel existUser = userService.loginUser(user.getUsername());
// response.setMessage("Login in successfully");
// response.setStatus(HttpStatus.OK);
// existUser.setPassword(null);
// response.setData(existUser);
return response;
}catch (Exception e){
return new ResponseModel(
"INTERNAL_SERVER_ERROR",
HttpStatus.INTERNAL_SERVER_ERROR,
null);
}
}
}
package vt.CS5934.SwitchRoom.hash;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class SHAModel {
String salt = getSalt();
public SHAModel() throws NoSuchAlgorithmException {
}
public String get_SHA_1_SecurePassword(String passwordToHash) {
String generatedPassword = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(salt.getBytes());
byte[] bytes = md.digest(passwordToHash.getBytes());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16)
.substring(1));
}
generatedPassword = sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return generatedPassword;
public byte[] getSHA(String input) throws NoSuchAlgorithmException
{
/* MessageDigest instance for hashing using SHA256 */
MessageDigest md = MessageDigest.getInstance("SHA-256");
/* digest() method called to calculate message digest of an input and return array of byte */
return md.digest(input.getBytes(StandardCharsets.UTF_8));
}
public String getSalt() throws NoSuchAlgorithmException {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[16];
sr.nextBytes(salt);
return salt.toString();
public String toHexString(byte[] hash)
{
/* Convert byte array of hash into digest */
BigInteger number = new BigInteger(1, hash);
/* Convert the digest into hex value */
StringBuilder hexString = new StringBuilder(number.toString(16));
/* Pad with leading zeros */
while (hexString.length() < 32)
{
hexString.insert(0, '0');
}
return hexString.toString();
}
}
......@@ -21,11 +21,11 @@ public class UserModel {
@Id
@Column(name="user_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int userId;
private Integer userId;
@Column(name="username",unique=true)
private String username;
@Column(name="password")
@Column(name="password", length = 1000)
private String password;
@Column(name="email")
......
......@@ -22,6 +22,8 @@ public interface UserRepository extends JpaRepository<UserModel, Integer> {
*/
UserModel findByUserId(long userId);
UserModel findByUsername(String username);
List<UserModel> findAll();
void deleteByUserId(long userId);
......
......@@ -4,11 +4,13 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vt.CS5934.SwitchRoom.hash.SHAModel;
import vt.CS5934.SwitchRoom.models.ExampleModel;
import vt.CS5934.SwitchRoom.models.UserModel;
import vt.CS5934.SwitchRoom.repositories.UserRepository;
import javax.transaction.Transactional;
import java.security.NoSuchAlgorithmException;
import java.util.List;
@Service
......@@ -19,6 +21,8 @@ public class UserService {
*/
private final Logger logger = LoggerFactory.getLogger(UserService.class);
private SHAModel shaModel = new SHAModel();
/**
* Autowired is a Spring feature that it will create or looking for the existing object in memory.
* It usually uses on Repository class, Service class, or some globe object in the class.
......@@ -26,10 +30,28 @@ public class UserService {
@Autowired
UserRepository userRepository;
public UserService() throws NoSuchAlgorithmException {
}
public UserModel addUserToDB(String username, String password, String email, String firstname, String lastname, String gender){
logger.info("Reached addNewExampleModelToDB()");
UserModel newUser = new UserModel(username, password, email, firstname, lastname, gender);
userRepository.save(newUser);
return newUser;
}
public UserModel loginUser(String username) {
logger.info("Reached loginUser() in UserService");
UserModel existUser = userRepository.findByUsername(username);
return existUser;
}
public String hashPassword(String password) throws NoSuchAlgorithmException {
String result = "";
result = shaModel.toHexString(shaModel.getSHA(password));
return result;
}
}
......@@ -23,11 +23,12 @@
<div class="underline-title"></div>
</div>
<form method="post" class="form">
<label for="user-email" style="padding-top: 13px">
<label for="user-name" style="padding-top: 13px">
&nbsp;Username
</label>
<input
id="user-email"
id="user-name"
v-model="userInformation.username"
class="form-content"
type="text"
name="username"
......@@ -40,6 +41,7 @@
</label>
<input
id="user-password"
v-model="userInformation.password"
class="form-content"
type="password"
name="password"
......@@ -49,7 +51,7 @@
<a href="#">
<legend id="forgot-pass">Forgot password?</legend>
</a>
<input id="submit-btn" type="submit" name="submit" value="LOGIN" />
<input id="submit-btn" type="submit" name="submit" value="LOGIN" @click.prevent="onSubmit" />
<router-link to="/register">
<div id="signup">Don't have account yet?</div>
</router-link>
......@@ -59,7 +61,36 @@
</div>
</template>
<script setup lang="ts"></script>
<script setup lang="ts">
import { ref, reactive } from "vue";
import * as UserService from "../services/UserService";
import { useRouter } from "vue-router";
import { UserModel } from "@/models/UserModel";
import { result } from "lodash";
const router = useRouter();
const user = ref(new UserModel());
const userInformation = reactive({
username: "",
password: "",
});
const onSubmit = async () => {
await UserService.loginUser(JSON.stringify(userInformation))
.then((result) => {
if (result.status == "OK") {
user.value = result.data
router.push("/login-main-page");
} else {
alert(result.message)
}
})
.catch((error) => {
alert(error)
})
;
};
</script>
<style scoped>
.content {
......
......@@ -93,16 +93,16 @@
/>
<div class="form-border"></div>
<!-- Gender Choose -->
<label for="user-gender" style="padding-top: 13px">
&nbsp;Gender
</label>
<div class="mb-2 flex items-center text-sm">
<el-radio-group v-model="userInformation.gender" class="ml-4">
<el-radio label="Male" size="large">Male</el-radio>
<el-radio label="Female" size="large">Female</el-radio>
</el-radio-group>
</div>
<!-- &lt;!&ndash; Gender Choose &ndash;&gt;-->
<!-- <label for="user-gender" style="padding-top: 13px">-->
<!-- &nbsp;Gender-->
<!-- </label>-->
<!-- <div class="mb-2 flex items-center text-sm">-->
<!-- <el-radio-group v-model="userInformation.gender" class="ml-4">-->
<!-- <el-radio label="Male" size="large">Male</el-radio>-->
<!-- <el-radio label="Female" size="large">Female</el-radio>-->
<!-- </el-radio-group>-->
<!-- </div>-->
<!-- terms agreement -->
<div>
......
export class UserModel {
public readonly userId: number;
public username: string;
public password: string | null;
public email: string;
public firstname: string;
public lastname: string;
public gender: string;
constructor(
userId = -1,
username = "",
password = "",
email = "",
firstname = "",
lastname = "",
gender = "",
) {
this.userId = userId;
this.username = username;
this.password = password;
this.email = email;
this.firstname = firstname;
this.lastname = lastname;
this.gender = gender;
}
}
\ No newline at end of file
......@@ -6,5 +6,10 @@ function postUserDataToServer(userData: any) {
// console.log(Server_URL + baseUrl + urlPath);
return serverHttpService.Post(baseUrl + urlPath, JSON.parse(userData));
}
function loginUser(userData: any) {
const urlPath = "/loginUser";
// console.log(Server_URL + baseUrl + urlPath);
return serverHttpService.Post(baseUrl + urlPath, JSON.parse(userData));
}
export { postUserDataToServer };
export { postUserDataToServer, loginUser };
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