Skip to content
Open

Core #85

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions exercise.wwwapi/Configuration/ConfigurationSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace exercise.wwwapi.Configuration
{
public class ConfigurationSettings : IConfigurationSettings
{
IConfiguration _configuration;
public ConfigurationSettings()
{
_configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
}
public string GetValue(string key)
{
return _configuration.GetValue<string>(key)!;
}
}
}
7 changes: 7 additions & 0 deletions exercise.wwwapi/Configuration/IConfigurationSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace exercise.wwwapi.Configuration
{
public interface IConfigurationSettings
{
string GetValue(string key);
}
}
30 changes: 30 additions & 0 deletions exercise.wwwapi/Data/DataContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using exercise.wwwapi.Models;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;

namespace exercise.wwwapi.Data
{
public class DataContext : DbContext
{
private string _connectionString;
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
_connectionString = configuration.GetValue<string>("ConnectionStrings:DefaultConnectionString")!;
this.Database.EnsureCreated();

}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(_connectionString);
optionsBuilder.LogTo(message => Debug.WriteLine(message));
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}

public DbSet<BlogPost> BlogPosts { get; set; }
public DbSet<User> Users { get; set; }
}
}
90 changes: 90 additions & 0 deletions exercise.wwwapi/EndPoints/AuthApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using exercise.wwwapi.Configuration;
using exercise.wwwapi.Models;
using exercise.wwwapi.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace exercise.wwwapi.EndPoints
{
public static class AuthApi
{
public static void ConfigureAuthApi(this WebApplication app)
{
app.MapPost("register", Register);
app.MapPost("login", Login);
app.MapGet("users", GetUsers);

}
[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
private static async Task<IResult> GetUsers(IRepository<User> service, ClaimsPrincipal user)
{
return TypedResults.Ok(service.GetAll());
}
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
private static async Task<IResult> Register(UserRequestDto request, IRepository<User> service)
{

//user exists
if (service.GetAll().Where(u => u.Username == request.Username).Any()) return Results.Conflict(new Payload<UserRequestDto>() { status = "Username already exists!", data = request });

string passwordHash = BCrypt.Net.BCrypt.HashPassword(request.Password);

var user = new User();

user.Username = request.Username;
user.PasswordHash = passwordHash;
user.Email = request.Email;

service.Insert(user);
service.Save();

return Results.Ok(new Payload<string>() { data = "Created Account" });
}

[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
private static async Task<IResult> Login(UserRequestDto request, IRepository<User> service, IConfigurationSettings config)
{
//user doesn't exist
if (!service.GetAll().Where(u => u.Username == request.Username).Any()) return Results.BadRequest(new Payload<UserRequestDto>() { status = "User does not exist", data = request });

User user = service.GetAll().FirstOrDefault(u => u.Username == request.Username)!;


if (!BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash))
{
return Results.BadRequest(new Payload<UserRequestDto>() { status = "Wrong Password", data = request });
}
string token = CreateToken(user, config);
return Results.Ok(new Payload<string>() { data = token });

}
private static string CreateToken(User user, IConfigurationSettings config)
{
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Sid, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.Email, user.Email),

};

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.GetValue("AppSettings:Token")));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.Now.AddDays(1),
signingCredentials: credentials
);
var jwt = new JwtSecurityTokenHandler().WriteToken(token);
return jwt;
}
}
}
64 changes: 64 additions & 0 deletions exercise.wwwapi/EndPoints/SecureApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using AutoMapper;
using exercise.wwwapi.Helpers;
using exercise.wwwapi.Models;
using exercise.wwwapi.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Win32;
using System.Security.Claims;

namespace exercise.wwwapi.EndPoints
{
public static class SecureApi
{
public static void ConfigureSecureApi(this WebApplication app)
{
app.MapGet("posts", GetPosts);
app.MapPost("posts", AddPost);
app.MapPut("posts{id}", UpdatePost);
}
[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
private static async Task<IResult> GetPosts(IRepository<BlogPost> repository, ClaimsPrincipal user, IMapper mapper)
{
return Results.Ok(new Payload<List<BlogPostRequestDto>>(mapper.Map<List<BlogPostRequestDto>>(repository.GetAll().ToList())));
}
[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
private static async Task<IResult> AddPost(IRepository<BlogPost> repository, BlogPostRequestDto newPost, ClaimsPrincipal user, IMapper mapper)
{
BlogPost blogPost = new BlogPost()
{
Text = newPost.Text,
UserId = user.UserRealId().Value,
};
repository.Insert(blogPost);
repository.Save();

var response = mapper.Map<BlogPostResponseDto>(blogPost);

return Results.Ok(new Payload<BlogPostResponseDto>(response));
}
[Authorize]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
private static async Task<IResult> UpdatePost(IRepository<BlogPost> repository, BlogPostRequestDto newPost, int id, ClaimsPrincipal user, IMapper mapper)
{
BlogPost blogPost = repository.GetById(id);
if (blogPost == null)
{
return Results.NotFound("Could not find blog post");
}
blogPost.Text = newPost.Text;
blogPost.UserId = user.UserRealId().Value;
repository.Update(blogPost);
repository.Save();

var response = mapper.Map<BlogPostResponseDto>(blogPost);

return Results.Ok(new Payload<BlogPostResponseDto>(response));
}
}
}
32 changes: 32 additions & 0 deletions exercise.wwwapi/Helpers/ClaimsPrincipalHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System.ComponentModel.DataAnnotations;
using System.Runtime.CompilerServices;
using System.Security.Claims;

namespace exercise.wwwapi.Helpers
{
public static class ClaimsPrincipalHelper
{
public static int? UserRealId(this ClaimsPrincipal user)
{
Claim? claim = user.FindFirst(ClaimTypes.Sid);
return int.Parse(claim?.Value);
}
public static string UserId(this ClaimsPrincipal user)
{
IEnumerable<Claim> claims = user.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier);
return claims.Count() >= 2 ? claims.ElementAt(1).Value : null;

}

public static string? Email(this ClaimsPrincipal user)
{
Claim? claim = user.FindFirst(ClaimTypes.Email);
return claim?.Value;
}
public static string? Role(this ClaimsPrincipal user)
{
Claim? claim = user.FindFirst(ClaimTypes.Role);
return claim?.Value;
}
}
}
14 changes: 14 additions & 0 deletions exercise.wwwapi/Helpers/MappingProfile.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using AutoMapper;
using exercise.wwwapi.Models;

namespace exercise.wwwapi.Helpers
{
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<BlogPost, BlogPostRequestDto>();
CreateMap<BlogPost, BlogPostResponseDto>();
}
}
}
20 changes: 20 additions & 0 deletions exercise.wwwapi/Models/BlogPost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace exercise.wwwapi.Models
{
public class BlogPost
{
[Column("id")]
[Key]
public int Id { get; set; }

[Column("text")]
public string Text { get; set; }

[ForeignKey("user_id")]
public int UserId { get; set; }

public User User { get; set; }
}
}
7 changes: 7 additions & 0 deletions exercise.wwwapi/Models/BlogPostRequestDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace exercise.wwwapi.Models
{
public class BlogPostRequestDto
{
public string Text { get; set; }
}
}
11 changes: 11 additions & 0 deletions exercise.wwwapi/Models/BlogPostResponseDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System.ComponentModel.DataAnnotations.Schema;

namespace exercise.wwwapi.Models
{
public class BlogPostResponseDto
{
public int Id { get; set; }
public string Text { get; set; }
public int UserId { get; set; }
}
}
19 changes: 19 additions & 0 deletions exercise.wwwapi/Models/Payload.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;

namespace exercise.wwwapi.Models
{
[NotMapped]
public class Payload<T> where T : class
{
public string status { get; set; } = "success";
public T data { get; set; }

public Payload(T data)
{
this.status = "success";
this.data = data;
}
public Payload() { }
}
}
17 changes: 17 additions & 0 deletions exercise.wwwapi/Models/User.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System.ComponentModel.DataAnnotations.Schema;

namespace exercise.wwwapi.Models
{
[Table("users")]
public class User
{
[Column("id")]
public int Id { get; set; }
[Column("username")]
public string Username { get; set; }
[Column("passwordhash")]
public string PasswordHash { get; set; }
[Column("email")]
public string Email { get; set; }
}
}
12 changes: 12 additions & 0 deletions exercise.wwwapi/Models/UserRequestDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations.Schema;

namespace exercise.wwwapi.Models
{
[NotMapped]
public class UserRequestDto
{
public required string Username { get; set; }
public required string Password { get; set; }
public required string Email { get; set; }
}
}
12 changes: 12 additions & 0 deletions exercise.wwwapi/Models/UserResponseDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations.Schema;

namespace exercise.wwwapi.Models
{
[NotMapped]
public class UserResponseDto
{
public string Username { get; set; }
public string PasswordHash { get; set; }
public string Email { get; set; }
}
}
Loading