profile gets data from db, changes to edituser

This commit is contained in:
LilleBRG 2025-03-25 14:24:36 +01:00
parent fccea25296
commit f42dcd743a
19 changed files with 209 additions and 86 deletions

View File

@ -1,5 +1,6 @@
using Api.DBAccess; using Api.DBAccess;
using Api.Models; using Api.Models;
using Api.Models.User;
using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
@ -22,6 +23,14 @@ namespace Api.BusinessLogic
_configuration = configuration; _configuration = configuration;
} }
public async Task<IActionResult> getUser(int userId)
{
User user = await _dbAccess.getUser(userId);
if (user == null || user.Id == 0) { return new ConflictObjectResult(new { message = "Could not find user" }); }
return new OkObjectResult(new { user.Id, user.UserName, user.Email });
}
public async Task<IActionResult> RegisterUser(User user) public async Task<IActionResult> RegisterUser(User user)
{ {
if (!new Regex(@".+@.+\..+").IsMatch(user.Email)) if (!new Regex(@".+@.+\..+").IsMatch(user.Email))
@ -47,7 +56,6 @@ namespace Api.BusinessLogic
return await _dbAccess.CreateUser(user); return await _dbAccess.CreateUser(user);
} }
public async Task<IActionResult> Login(Login login) public async Task<IActionResult> Login(Login login)
{ {
User user = await _dbAccess.Login(login); User user = await _dbAccess.Login(login);
@ -59,30 +67,43 @@ namespace Api.BusinessLogic
if (user.Password == hashedPassword) if (user.Password == hashedPassword)
{ {
var token = GenerateJwtToken(user); var token = GenerateJwtToken(user);
return new OkObjectResult(new { token, user.UserName, user.Id }); return new OkObjectResult(new { token, user.Id});
} }
return new ConflictObjectResult(new { message = "Invalid password" }); return new ConflictObjectResult(new { message = "Invalid password" });
} }
public async Task<IActionResult> EditProfile(User user, int userId) public async Task<IActionResult> EditProfile(EditUserRequest userRequest, int userId)
{ {
if (!new Regex(@".+@.+\..+").IsMatch(user.Email)) if (!new Regex(@".+@.+\..+").IsMatch(userRequest.Email))
{ {
return new ConflictObjectResult(new { message = "Invalid email address" }); return new ConflictObjectResult(new { message = "Invalid email address" });
} }
if (!PasswordSecurity(user.Password))
return await _dbAccess.UpdateUser(userRequest, userId);
}
public async Task<IActionResult> changePassword(ChangePasswordRequest passwordRequest, int userId)
{
var user = await _dbAccess.ReadUser(userId);
string hashedPassword = ComputeHash(passwordRequest.OldPassword, SHA256.Create(), user.Salt);
if (user.Password != hashedPassword)
{ {
return new ConflictObjectResult(new { message = "Password is not up to the security standard" }); return new ConflictObjectResult(new { message = "Old password is incorrect" });
} }
var profile = await _dbAccess.ReadUser(userId); if (!PasswordSecurity(passwordRequest.NewPassword))
{
return new ConflictObjectResult(new { message = "New password is not up to the security standard" });
}
string hashedPassword = ComputeHash(user.Password, SHA256.Create(), profile.Salt); string hashedNewPassword = ComputeHash(passwordRequest.NewPassword, SHA256.Create(), user.Salt);
user.Password = hashedPassword;
return await _dbAccess.UpdateUser(user, userId); return await _dbAccess.updatePassword(hashedNewPassword, userId);
} }
public async Task<IActionResult> DeleteUser(int userId) public async Task<IActionResult> DeleteUser(int userId)

View File

@ -1,12 +1,8 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Api.Models; using Api.Models;
using Api.DBAccess;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Api.BusinessLogic; using Api.BusinessLogic;
using Api.Models.User;
namespace Api.Controllers namespace Api.Controllers
{ {
@ -21,31 +17,43 @@ namespace Api.Controllers
_userLogic = userLogic; _userLogic = userLogic;
} }
[HttpPost("Login")] //[Authorize]
[HttpGet("{userId}")]
public async Task<IActionResult> GetUSer(int userId)
{
return await _userLogic.getUser(userId);
}
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] Login login) public async Task<IActionResult> Login([FromBody] Login login)
{ {
return await _userLogic.Login(login); return await _userLogic.Login(login);
} }
[HttpPost("Create")] [HttpPost("create")]
public async Task<IActionResult> CreateUser([FromBody] User user) public async Task<IActionResult> CreateUser([FromBody] User user)
{ {
return await _userLogic.RegisterUser(user); return await _userLogic.RegisterUser(user);
} }
[Authorize] //[Authorize]
[HttpPut("Edit/{userId}")] [HttpPut("edit/{userId}")]
public async Task<IActionResult> EditUser([FromBody] User user, int userId) public async Task<IActionResult> EditUser([FromBody] EditUserRequest userRequest, int userId)
{ {
return await _userLogic.EditProfile(user, userId); return await _userLogic.EditProfile(userRequest, userId);
}
//[Authorize]
[HttpPut("change-password/{userId}")]
public async Task<IActionResult> changePassword([FromBody] ChangePasswordRequest passwordRequest, int userId)
{
return await _userLogic.changePassword(passwordRequest, userId);
} }
[Authorize] [Authorize]
[HttpDelete("Delete/{userId}")] [HttpDelete("delete/{userId}")]
public async Task<IActionResult> DeleteUser(int userId) public async Task<IActionResult> DeleteUser(int userId)
{ {
return await _userLogic.DeleteUser(userId); return await _userLogic.DeleteUser(userId);
} }
} }
} }

View File

@ -5,6 +5,7 @@ using System.Runtime.Intrinsics.Arm;
using System.Security.Cryptography; using System.Security.Cryptography;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using static System.Runtime.InteropServices.JavaScript.JSType; using static System.Runtime.InteropServices.JavaScript.JSType;
using Api.Models.User;
namespace Api.DBAccess namespace Api.DBAccess
@ -18,6 +19,12 @@ namespace Api.DBAccess
_context = context; _context = context;
} }
public async Task<User> getUser(int userId)
{
return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
}
public async Task<IActionResult> CreateUser(User user) public async Task<IActionResult> CreateUser(User user)
{ {
var users = await _context.Users.ToListAsync(); var users = await _context.Users.ToListAsync();
@ -64,7 +71,7 @@ namespace Api.DBAccess
return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId); return await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
} }
public async Task<IActionResult> UpdateUser(User user, int userId) public async Task<IActionResult> UpdateUser(EditUserRequest user, int userId)
{ {
var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId); var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
var users = await _context.Users.ToListAsync(); var users = await _context.Users.ToListAsync();
@ -73,12 +80,12 @@ namespace Api.DBAccess
foreach (var item in users) foreach (var item in users)
{ {
if (item.UserName == user.UserName) if (item.UserName == user.UserName && userId != item.Id)
{ {
return new ConflictObjectResult(new { message = "Username is already in use." }); return new ConflictObjectResult(new { message = "Username is already in use." });
} }
if (item.Email == user.Email) if (item.Email == user.Email && userId != item.Id)
{ {
return new ConflictObjectResult(new { message = "Email is being used already" }); return new ConflictObjectResult(new { message = "Email is being used already" });
} }
@ -88,7 +95,20 @@ namespace Api.DBAccess
profile.Email = user.Email; profile.Email = user.Email;
profile.Password = user.Password; bool saved = await _context.SaveChangesAsync() == 1;
if (saved) { return new OkObjectResult(profile); }
return new ConflictObjectResult(new { message = "Could not save to database" });
}
public async Task<IActionResult> updatePassword(string newPassword, int userId)
{
var profile = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId);
if (profile == null) { return new ConflictObjectResult(new { message = "User does not exist" }); }
profile.Password = newPassword;
bool saved = await _context.SaveChangesAsync() == 1; bool saved = await _context.SaveChangesAsync() == 1;

View File

@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Api.Models; using Api.Models;
using Api.Models.User;
namespace Api namespace Api
{ {

View File

@ -0,0 +1,8 @@
namespace Api.Models.User
{
public class ChangePasswordRequest
{
public string OldPassword { get; set; }
public string NewPassword { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace Api.Models.User
{
public class EditUserRequest
{
public string UserName { get; set; }
public string Email { get; set; }
}
}

View File

@ -1,4 +1,4 @@
namespace Api.Models namespace Api.Models.User
{ {
public class User public class User
{ {

View File

@ -5,6 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Temperature-Alarm-Web</title> <title>Temperature-Alarm-Web</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<link rel="stylesheet" href="/styles/auth.css">
<link rel="stylesheet" href="/styles/home.css" /> <link rel="stylesheet" href="/styles/home.css" />
<script type="module" src="/scripts/home.js"></script> <script type="module" src="/scripts/home.js"></script>
</head> </head>

View File

@ -4,6 +4,8 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<title>Temperature Alarm</title> <title>Temperature Alarm</title>
<link rel="stylesheet" href="/styles/frontpage.css"> <link rel="stylesheet" href="/styles/frontpage.css">
<link rel="stylesheet" href="/styles/auth.css">
</head> </head>
<body> <body>
<main> <main>

View File

@ -21,7 +21,7 @@
<button type="submit">Login</button> <button type="submit">Login</button>
<div class="details"> <div class="details">
<label> <label>
<input type="checkbox" name="remember"> Remember me <input type="checkbox" name="remember" id="rememberId"> Remember me
</label> </label>
<span> <span>
Dont have an account? <a href="/register">Register</a> Dont have an account? <a href="/register">Register</a>

View File

@ -10,6 +10,13 @@
</head> </head>
<body> <body>
<div id="container"> <div id="container">
<div class="topnav">
<a class="active" href="/home/index.html">Home</a>
<div style="display: flex; justify-content: flex-end;">
<a class="" href="/home/index.html">Devices</a>
<a class="" href="/profile/index.html">Profile</a>
</div>
</div>
<div id="profileCard"></div> <div id="profileCard"></div>
<div class="btnContainer"> <div class="btnContainer">
<button class="btn" id="openEditModal">Edit</button> <button class="btn" id="openEditModal">Edit</button>
@ -32,7 +39,6 @@
<button type="submit">Save Changes</button> <button type="submit">Save Changes</button>
<div class="error-text" id="form-error-edit"></div>
</div> </div>
</form> </form>
</div> </div>
@ -55,7 +61,7 @@
<button type="submit">Change Password</button> <button type="submit">Change Password</button>
<div class="error-text" id="form-error-password"></div> <div id="form-error"></div>
</div> </div>
</form> </form>
</div> </div>

View File

@ -13,9 +13,21 @@ document.getElementById("loginForm").addEventListener("submit", function(event)
if (response.error) { if (response.error) {
document.getElementById("form-error").innerText = response.error; document.getElementById("form-error").innerText = response.error;
document.getElementById("form-error").style.display = "block"; document.getElementById("form-error").style.display = "block";
return; return;
} }
else{
if (typeof(Storage) !== "undefined") {
if(document.getElementById("rememberId").checked == true){
localStorage.setItem("id", response.id);
localStorage.setItem("rememberLogin", true);
}
else{
localStorage.setItem("rememberLogin", false);
sessionStorage.setItem("id", response.id);
}
}
}
location.href = "/home"; location.href = "/home";
}); });

View File

@ -1,15 +1,30 @@
import { profileData } from "../mockdata/profile.mockdata.js"; import { profileData } from "../mockdata/profile.mockdata.js";
import { get } from "./services/users.service.js";
import { update } from "./services/users.service.js";
import { updatePassword } from "./services/users.service.js";
var table = document.getElementById(`profileCard`); let idlocation = localStorage.getItem("rememberLogin")
let id;
if(idlocation){
id = localStorage.getItem("id");
}
else{
id = localStorage.getItem("id");
}
get(id).then(res => {
var table = document.getElementById(`profileCard`);
table.innerHTML += ` table.innerHTML += `
<div class="pfp"> <div class="pfp">
<img style="width:200px; height:200px" src="${profileData.pfp}"> <img style="width:200px; height:200px" src="${profileData.pfp}">
</div> </div>
<div class="userData"> <div class="userData">
<h2>${profileData.username}</h2> <h2>${res.userName}</h2>
<h2>${profileData.email}</h2> <h2>${res.email}</h2>
</div> </div>
</div>`; </div>`;
})
var pswModal = document.getElementById("PasswordModal"); var pswModal = document.getElementById("PasswordModal");
var editModal = document.getElementById("editModal"); var editModal = document.getElementById("editModal");
@ -33,20 +48,22 @@ window.onclick = (event) => {
if (event.target == pswModal || event.target == editModal) { if (event.target == pswModal || event.target == editModal) {
pswModal.style.display = "none"; pswModal.style.display = "none";
editModal.style.display = "none"; editModal.style.display = "none";
document.getElementById("form-error").innerText = "";
document.getElementById("form-error").style.display = "none";
} }
}; };
document.getElementById("editForm").addEventListener("submit", function(event) { document.getElementById("editForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevents default form submission event.preventDefault(); // Prevents default form submission
document.getElementById("form-error-edit").style.display = "none"; document.getElementById("form-error").style.display = "none";
// Get form values // Get form values
const email = document.getElementById("email").value; const email = document.getElementById("email").value;
const username = document.getElementById("uname").value; const username = document.getElementById("uname").value;
// Call function with form values // Call function with form values
update(email, username) update(email, username, id)
.then(response => { .then(response => {
if (response?.error) { if (response?.error) {
document.getElementById("form-error").innerText = response.error; document.getElementById("form-error").innerText = response.error;
@ -55,37 +72,33 @@ document.getElementById("editForm").addEventListener("submit", function(event) {
return; return;
} }
location.href = "/login"; location.href = "/profile";
}); });
}); });
document.getElementById("PasswordForm").addEventListener("submit", function(event) { document.getElementById("PasswordForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevents default form submission event.preventDefault(); // Prevents default form submission
document.getElementById("form-error-password").style.display = "none"; document.getElementById("form-error").style.display = "none";
// Get form values
const oldPassword = document.getElementById("oldpsw").value; const oldPassword = document.getElementById("oldpsw").value;
const newPassword = document.getElementById("psw").value; const newPassword = document.getElementById("psw").value;
const repeatPassword = document.getElementById("rpsw").value; const repeatPassword = document.getElementById("rpsw").value;
if (newPassword !== repeatPassword) { if (newPassword !== repeatPassword) {
let errorDiv = document.getElementById("form-error-password"); let errorDiv = document.getElementById("form-error");
errorDiv.style.display = "block"; errorDiv.style.display = "block";
errorDiv.innerText = "Passwords do not match!"; errorDiv.innerText = "Passwords do not match!";
return; return;
} }
// Call function with form values updatePassword(oldPassword, newPassword, id)
update(email, username)
.then(response => { .then(response => {
if (response?.error) { //error messages do not work
document.getElementById("form-error").innerText = response.error; if (response.error) {
document.getElementById("form-error").innerText = response.message;
document.getElementById("form-error").style.display = "block"; document.getElementById("form-error").style.display = "block";
return; return;
} }
location.href = "/login";
}); });
}); });

View File

@ -1,6 +1,18 @@
import { address } from "../../shared/constants.js"; import { address } from "../../shared/constants.js";
import { handleResponse } from "../../shared/utils.js"; import { handleResponse } from "../../shared/utils.js";
export function get(userId) {
return fetch(`${address}/user/${userId}`, {
method: "GET",
headers: {
"Content-Type": "application/json"
},
})
.then(handleResponse)
.catch(err => { error: err.message });
}
export function login(usernameOrEmail, password) { export function login(usernameOrEmail, password) {
return fetch(`${address}/user/login`, { return fetch(`${address}/user/login`, {
method: "POST", method: "POST",
@ -28,9 +40,9 @@ export function create(email, username, password, repeatPassword){
.catch(err => { error: err.message }); .catch(err => { error: err.message });
} }
export function update(email, username){ export function update(email, username, userId){
return fetch(`${address}/user/update`, { return fetch(`${address}/user/edit/${userId}`, {
method: "PATCH", method: "PUT",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json"
}, },
@ -40,9 +52,9 @@ export function update(email, username){
.catch(err => { error: err.message }); .catch(err => { error: err.message });
} }
export function updatePassword(oldPassword, newPassword){ export function updatePassword(oldPassword, newPassword, userId){
return fetch(`${address}/user/update-password`, { return fetch(`${address}/user/change-password/${userId}`, {
method: "PATCH", method: "PUT",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json"
}, },

View File

@ -1 +1 @@
export const address = "hhttps://temperature.mercantec.tech/api" export const address = "http://127.0.0.1:5000/api"

View File

@ -1,7 +1,32 @@
body { body {
font-family: Arial, Helvetica, sans-serif; font-family: Arial, Helvetica, sans-serif;
margin: 0;
} }
.topnav {
overflow: hidden;
background-color: #333;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #04aa6d;
color: white;
}
/* Full-width input fields */ /* Full-width input fields */
input[type=text], input[type=password], input[type=email] { input[type=text], input[type=password], input[type=email] {
width: 100%; width: 100%;
@ -15,12 +40,12 @@ input[type=text], input[type=password], input[type=email] {
/* Set a style for all buttons */ /* Set a style for all buttons */
button { button {
background-color: #04AA6D; background-color: #04AA6D;
color: white;
padding: 14px 20px; padding: 14px 20px;
margin: 8px 0; margin: 8px 0;
border: none; border: none;
cursor: pointer; cursor: pointer;
width: 100%; width: 100%;
border-radius: 20px;
} }
button:hover { button:hover {
@ -49,6 +74,3 @@ button:hover {
margin-top: 1rem; margin-top: 1rem;
} }
button{
border-radius: 20px;
}

View File

@ -4,7 +4,6 @@
} }
body { body {
margin: 0;
font-family: sans-serif; font-family: sans-serif;
} }

View File

@ -1,5 +1,4 @@
body { body {
margin: 0;
font-family: Arial, Helvetica, sans-serif; font-family: Arial, Helvetica, sans-serif;
} }
@ -8,30 +7,6 @@ body {
opacity: 100%; opacity: 100%;
} }
.topnav {
overflow: hidden;
background-color: #333;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #04aa6d;
color: white;
}
table { table {
font-family: arial, sans-serif; font-family: arial, sans-serif;
border-collapse: collapse; border-collapse: collapse;

View File

@ -49,8 +49,23 @@ h2{
padding: 20px; padding: 20px;
border: 1px solid #888; border: 1px solid #888;
width: 80%; width: 80%;
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
} }
/* Add Animation */
@-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
@keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
/* The Close Button */ /* The Close Button */
.close { .close {
color: #aaaaaa; color: #aaaaaa;