Compare commits

...

3 Commits

Author SHA1 Message Date
LilleBRG
8f6f332292 device table header 2025-03-25 16:20:08 +01:00
LilleBRG
a3f3d8f861 changes to updateuser, added logout button 2025-03-25 16:11:14 +01:00
LilleBRG
f42dcd743a profile gets data from db, changes to edituser 2025-03-25 14:24:36 +01:00
27 changed files with 329 additions and 122 deletions

View File

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

View File

@ -1,12 +1,8 @@
using Microsoft.AspNetCore.Mvc;
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 Api.BusinessLogic;
using Api.Models.User;
namespace Api.Controllers
{
@ -21,31 +17,43 @@ namespace Api.Controllers
_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)
{
return await _userLogic.Login(login);
}
[HttpPost("Create")]
[HttpPost("create")]
public async Task<IActionResult> CreateUser([FromBody] User user)
{
return await _userLogic.RegisterUser(user);
}
[Authorize]
[HttpPut("Edit/{userId}")]
public async Task<IActionResult> EditUser([FromBody] User user, int userId)
//[Authorize]
[HttpPut("edit/{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]
[HttpDelete("Delete/{userId}")]
[HttpDelete("delete/{userId}")]
public async Task<IActionResult> DeleteUser(int userId)
{
return await _userLogic.DeleteUser(userId);
}
}
}

View File

@ -5,6 +5,7 @@ using System.Runtime.Intrinsics.Arm;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Mvc;
using static System.Runtime.InteropServices.JavaScript.JSType;
using Api.Models.User;
namespace Api.DBAccess
@ -18,6 +19,12 @@ namespace Api.DBAccess
_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)
{
var users = await _context.Users.ToListAsync();
@ -64,7 +71,7 @@ namespace Api.DBAccess
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 users = await _context.Users.ToListAsync();
@ -73,22 +80,39 @@ namespace Api.DBAccess
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." });
}
if (item.Email == user.Email)
if (item.Email == user.Email && userId != item.Id)
{
return new ConflictObjectResult(new { message = "Email is being used already" });
}
}
profile.UserName = user.UserName;
if(user.Email != "" && user.Email != null)
profile.Email = user.Email;
profile.Email = user.Email;
if (user.UserName != "" && user.UserName != null)
profile.UserName = user.UserName;
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;

View File

@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore;
using Api.Models;
using Api.Models.User;
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
{

View File

@ -0,0 +1,39 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Temperature-Alarm-Web</title>
<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/devices.css" />
<script defer type="module" src="/scripts/devices.js"></script>
<script defer type="module" src="/shared/utils.js"></script>
</head>
<body>
<div id="container">
<div class="topnav">
<a href="/home/index.html">Home</a>
<a class="active" href="/devices/index.html">Devices</a>
<div style="display: flex; justify-content: flex-end;">
<a href="/profile/index.html">Profile</a>
<span class="logoutContainer">
<img class="logout" src="/img/logout.png">
</span>
</div>
</div>
<div class="addDeviceContainer">
<button class="addDevice">Add Device</button>
</div>
<table>
<tr>
<th>Id</th>
<th>Placement</th>
<th>Latest Meassurement</th>
</tr>
<tbody id="deviceTable"></tbody>
</table>
</div>
</body>
</html>

View File

@ -5,17 +5,22 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Temperature-Alarm-Web</title>
<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" />
<script type="module" src="/scripts/home.js"></script>
<script defer type="module" src="/shared/utils.js"></script>
</head>
<body>
<div id="container">
<div class="topnav">
<a class="active" href="/home/index.html">Home</a>
<a href="/devices/index.html">Devices</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>
<a href="/profile/index.html">Profile</a>
<span class="logoutContainer">
<img class="logout" src="/img/logout.png">
</span>
</div>
</div>
<div class="chartContainer">

BIN
frontend/img/logout.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

View File

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

View File

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

View File

@ -7,9 +7,20 @@
<link rel="stylesheet" href="/styles/auth.css">
<link rel="stylesheet" href="/styles/profile.css">
<script defer type="module" src="/scripts/profile.js"></script>
<script defer type="module" src="/shared/utils.js"></script>
</head>
<body>
<div id="container">
<div class="topnav">
<a href="/home/index.html">Home</a>
<a href="/devices/index.html">Devices</a>
<div style="display: flex; justify-content: flex-end;">
<a class="active" href="/profile/index.html">Profile</a>
<span class="logoutContainer">
<img class="logout" src="/img/logout.png">
</span>
</div>
</div>
<div id="profileCard"></div>
<div class="btnContainer">
<button class="btn" id="openEditModal">Edit</button>
@ -25,14 +36,13 @@
<form id="editForm">
<div class="form-container">
<label for="email"><b>Email</b></label>
<input type="email" placeholder="Enter email "id="email" required>
<input type="email" placeholder="Enter email "id="email">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter username" id="uname" required>
<input type="text" placeholder="Enter username" id="uname">
<button type="submit">Save Changes</button>
<div class="error-text" id="form-error-edit"></div>
</div>
</form>
</div>
@ -55,7 +65,7 @@
<button type="submit">Change Password</button>
<div class="error-text" id="form-error-password"></div>
<div id="form-error"></div>
</div>
</form>
</div>

View File

@ -10,7 +10,7 @@
<body>
<form id="registerForm">
<div class="form-container">
<h1>Create Account</h1>
<h1>Sign Up</h1>
<label for="email"><b>Email</b></label>
<input type="email" placeholder="Enter email "id="email" required>

View File

@ -0,0 +1,26 @@
import { getDevicesOnUserId } from "./services/devices.service.js";
let idlocation = localStorage.getItem("rememberLogin")
let id;
if(idlocation){
id = localStorage.getItem("id");
}
else{
id = localStorage.getItem("id");
}
getDevicesOnUserId(id).then(res => {
buildTable(res)
})
function buildTable(data) {
var table = document.getElementById(`deviceTable`);
data.forEach((device) => {
var row = ` <tr>
<td>Name</td>
<td class="${color}">${device.id}</td>
<td>${device.name}</td>
</tr>`;
table.innerHTML += row;
});
}

View File

@ -61,24 +61,4 @@ function buildTable(data) {
</tr>`;
table.innerHTML += row;
});
}
// Get the modal
var modal = document.getElementById("chartModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function () {
modal.style.display = "block";
};
// When the user clicks on <span> (x), close the modal
span.onclick = function () {
modal.style.display = "none";
};
// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
};
}

View File

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

View File

@ -1,15 +1,24 @@
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 id = localStorage.getItem("id");
get(id).then(res => {
var table = document.getElementById(`profileCard`);
table.innerHTML += `
<div class="pfp">
<img style="width:200px; height:200px" src="${profileData.pfp}">
</div>
<div class="userData">
<h2>${profileData.username}</h2>
<h2>${profileData.email}</h2>
<h2>${res.userName}</h2>
<h2>${res.email}</h2>
</div>
</div>`;
})
var pswModal = document.getElementById("PasswordModal");
var editModal = document.getElementById("editModal");
@ -25,6 +34,8 @@ document.querySelectorAll(".close").forEach(closeBtn => {
closeBtn.onclick = () => {
pswModal.style.display = "none";
editModal.style.display = "none";
document.getElementById("form-error").innerText = "";
document.getElementById("form-error").style.display = "none";
};
});
@ -33,20 +44,22 @@ window.onclick = (event) => {
if (event.target == pswModal || event.target == editModal) {
pswModal.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) {
event.preventDefault(); // Prevents default form submission
document.getElementById("form-error-edit").style.display = "none";
document.getElementById("form-error").style.display = "none";
// Get form values
const email = document.getElementById("email").value;
const username = document.getElementById("uname").value;
// Call function with form values
update(email, username)
update(email, username, id)
.then(response => {
if (response?.error) {
document.getElementById("form-error").innerText = response.error;
@ -55,37 +68,33 @@ document.getElementById("editForm").addEventListener("submit", function(event) {
return;
}
location.href = "/login";
location.href = "/profile";
});
});
document.getElementById("PasswordForm").addEventListener("submit", function(event) {
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 newPassword = document.getElementById("psw").value;
const repeatPassword = document.getElementById("rpsw").value;
if (newPassword !== repeatPassword) {
let errorDiv = document.getElementById("form-error-password");
let errorDiv = document.getElementById("form-error");
errorDiv.style.display = "block";
errorDiv.innerText = "Passwords do not match!";
return;
}
// Call function with form values
update(email, username)
updatePassword(oldPassword, newPassword, id)
.then(response => {
if (response?.error) {
document.getElementById("form-error").innerText = response.error;
//error messages do not work
if (response.error) {
document.getElementById("form-error").innerText = response.message;
document.getElementById("form-error").style.display = "block";
return;
}
location.href = "/login";
});
});

View File

@ -1,12 +1,11 @@
import { address } from "../../shared/constants";
import { address } from "../../shared/constants.js";
export function getDevicesOnUserId(id) {
fetch(`${address}/get-on-user-id`, {
export function getDevicesOnUserId(userId) {
fetch(`${address}/device/${userId}`, {
method: "GET",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ id: id })
})
.then(response => response.json())
.then(data => console.log("Success:", data))

View File

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

@ -10,3 +10,9 @@ export async function handleResponse(response) {
return { error: "Request failed with HTTP code " + response.status };
}
document.querySelectorAll(".logoutContainer").forEach(closeBtn => {
closeBtn.onclick = () => {
localStorage.clear();
window.location.href = "/index.html";
};
});

View File

@ -1,5 +1,32 @@
body {
font-family: Arial, Helvetica, sans-serif;
margin: 0;
}
.topnav {
overflow: hidden;
background-color: #333;
}
.topnav a {
height: 20px;
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover, .topnav span:hover {
background-color: #ddd;
color: black;
cursor: pointer;
}
.topnav a.active {
background-color: #04aa6d;
color: white;
}
/* Full-width input fields */
@ -15,12 +42,12 @@ input[type=text], input[type=password], input[type=email] {
/* Set a style for all buttons */
button {
background-color: #04AA6D;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
border-radius: 20px;
}
button:hover {
@ -35,7 +62,7 @@ button:hover {
.details {
display: flex;
justify-content: space-between;
justify-content: flex-end;
margin-top: 0.5rem;
}
@ -49,6 +76,15 @@ button:hover {
margin-top: 1rem;
}
button{
border-radius: 20px;
.logoutContainer{
display: flex;
justify-content: center;
align-items: center;
width: 50px;
}
.logout{
width: 20px;
height: 24px;
}

View File

@ -0,0 +1,28 @@
table {
margin: 20px;
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
.addDeviceContainer{
margin-top: 20px;
display: flex;
justify-content: flex-end;
}
.addDevice{
width: 120px;
margin: 0 20px 0 0;
}

View File

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

View File

@ -1,5 +1,4 @@
body {
margin: 0;
font-family: Arial, Helvetica, sans-serif;
}
@ -8,31 +7,8 @@ body {
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 {
margin: 20px;
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;

View File

@ -49,8 +49,23 @@ h2{
padding: 20px;
border: 1px solid #888;
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 */
.close {
color: #aaaaaa;