Skip to content

Commit 6cdd194

Browse files
committed
Integrate with Postgres db
1 parent 978a4a9 commit 6cdd194

10 files changed

Lines changed: 174 additions & 3 deletions

File tree

RequestTests.paw

5.75 KB
Binary file not shown.

postgresscripts/Startdb.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pg_ctl start -D /Users/AntonEfimenko/Documents/Programming/postgresdb

postgresscripts/stopdb.sh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
#pg_ctl stop [-W] [-t seconds] [-s] [-D datadir] [-m s[mart] | f[ast] | i[mmediate] ]
2+
pg_ctl stop -D /Users/AntonEfimenko/Documents/Programming/postgresdb -m i

src/SimpleToDoService/AppSettings.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,6 @@
88
}
99
},
1010
"DbContextSettings" :{
11-
"ConnectionString" : "User ID=AntonEfimenko;Password=pass;Host=localhost;Port=5432;Database=SimpleToDoDB;Pooling=true;"
11+
"ConnectionString" : "User ID=AntonEfimenko;Password=;Host=localhost;Port=5432;Database=SimpleToDoDB;Pooling=true;"
1212
}
1313
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
using System;
2+
using System.Text;
3+
using System.Threading.Tasks;
4+
using Microsoft.AspNetCore.Http;
5+
using Microsoft.Net.Http.Headers;
6+
using System.Linq;
7+
using Microsoft.EntityFrameworkCore;
8+
9+
10+
namespace SimpleToDoService
11+
{
12+
public class BasicAuthMiddleware
13+
{
14+
private readonly RequestDelegate next;
15+
private ToDoContext dbContext;
16+
17+
public BasicAuthMiddleware(RequestDelegate next, ToDoContext databaseContext)
18+
{
19+
this.next = next;
20+
dbContext = databaseContext;
21+
}
22+
23+
public async Task Invoke(HttpContext context)
24+
{
25+
var authHeader = (string)context.Request.Headers["Authorization"];
26+
if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
27+
{
28+
var token = authHeader.Substring("Basic ".Length).Trim();
29+
var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
30+
var credentials = credentialstring.Split(':');
31+
var user = credentials.FirstOrDefault();
32+
var password = credentials.Skip(1).FirstOrDefault();
33+
34+
var currentUser = dbContext.Users.Where(o => o.Email == user && o.Password == password).FirstOrDefault();
35+
if (currentUser != null)
36+
{
37+
context.Items.Add("UserId", currentUser.Id);
38+
}
39+
else
40+
{
41+
context.Response.StatusCode = 401; //Unauthorized
42+
var jsonString = "{ \"Error\" : \"Incorrect user name or password\" }";
43+
context.Response.ContentType = new MediaTypeHeaderValue("application/json").ToString();
44+
await context.Response.WriteAsync(jsonString, Encoding.UTF8);
45+
return;
46+
}
47+
}
48+
else
49+
{
50+
context.Response.StatusCode = 401; //Unauthorized
51+
var jsonString = "{ \"Error\" : \"Authorization header missed\" }";
52+
context.Response.ContentType = new MediaTypeHeaderValue("application/json").ToString();
53+
await context.Response.WriteAsync(jsonString, Encoding.UTF8);
54+
return;
55+
}
56+
57+
await next.Invoke(context);
58+
}
59+
}
60+
61+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
CREATE TABLE ToDoUser (
2+
Id serial PRIMARY KEY,
3+
FirstName varchar(255) NOT NULL,
4+
LastName varchar(255) NOT NULL,
5+
Email varchar(255) NOT NULL,
6+
Password varchar(255) NOT NULL
7+
);
8+
9+
CREATE TABLE ToDoEntry (
10+
Id serial PRIMARY KEY,
11+
Completed BOOL NOT NULL,
12+
Description varchar(255) NOT NULL,
13+
Notes varchar(4000),
14+
Owner serial REFERENCES ToDoUser (id)
15+
);

src/SimpleToDoService/SimpleToDoService.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
<None Include="AppSettings.json">
6767
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
6868
</None>
69+
<None Include="DbScripts\CreateTables.sql" />
6970
</ItemGroup>
7071
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
7172
</Project>

src/SimpleToDoService/Startup.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using Microsoft.AspNetCore.Builder;
66
using Microsoft.AspNetCore.Hosting;
77
using Microsoft.AspNetCore.Http;
8+
using Microsoft.EntityFrameworkCore;
89
using Microsoft.Extensions.Configuration;
910
using Microsoft.Extensions.DependencyInjection;
1011
using Microsoft.Extensions.Logging;
@@ -30,7 +31,7 @@ public void ConfigureServices(IServiceCollection services)
3031

3132
var connectionString = Configuration["DbContextSettings:ConnectionString"];
3233
Console.WriteLine(connectionString);
33-
//services.AddDbContext<DatabaseContext>(opts => opts.UseNpgsql(connectionString));
34+
services.AddDbContext<ToDoContext>(opts => opts.UseNpgsql(connectionString));
3435
}
3536

3637
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
@@ -40,6 +41,8 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
4041
app.UseDeveloperExceptionPage();
4142
}
4243

44+
app.UseMiddleware<BasicAuthMiddleware>();
45+
4346
app.UseMvc();
4447
//app.UseMiddleware<HeaderCheckMiddleware>();
4548
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
using System;
2+
using System.ComponentModel.DataAnnotations;
3+
using System.ComponentModel.DataAnnotations.Schema;
4+
using Microsoft.EntityFrameworkCore;
5+
6+
namespace SimpleToDoService
7+
{
8+
public class ToDoContext : DbContext
9+
{
10+
11+
public ToDoContext(DbContextOptions<ToDoContext> options) : base(options) { }
12+
13+
public DbSet<User> Users { get; set; }
14+
15+
public DbSet<ToDoEntry> ToDoEntries { get; set; }
16+
}
17+
18+
[Table("todouser")]
19+
public class User
20+
{
21+
[Key]
22+
[Column("id")]
23+
[Required]
24+
public int Id { get; set; }
25+
26+
[MaxLength(255)]
27+
[Column("firstname")]
28+
[Required]
29+
public string FirstName { get; set; }
30+
31+
[MaxLength(255)]
32+
[Column("lastname")]
33+
[Required]
34+
public string LastName { get; set; }
35+
36+
[MaxLength(255)]
37+
[Column("email")]
38+
[Required]
39+
public string Email { get; set; }
40+
41+
[MaxLength(255)]
42+
[Column("password")]
43+
[Required]
44+
public string Password { get; set; }
45+
}
46+
47+
48+
[Table("todoentry")]
49+
public class ToDoEntry
50+
{
51+
[Key]
52+
[Column("id")]
53+
[Required]
54+
public int Id { get; set; }
55+
56+
[Column("completed")]
57+
[Required]
58+
public bool Completed { get; set; }
59+
60+
[Column("description")]
61+
[Required]
62+
[MaxLength(255)]
63+
public string Description { get; set; }
64+
65+
[Column("notes")]
66+
[MaxLength(4000)]
67+
public string Notes { get; set; }
68+
69+
[ForeignKey("owner")]
70+
[Required]
71+
public User User { get; set; }
72+
}
73+
}
Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,29 @@
11
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
24
using Microsoft.AspNetCore.Mvc;
5+
using Microsoft.EntityFrameworkCore;
36

47
namespace SimpleToDoService
58
{
69
[Route("api/[controller]")]
710
public class ToDoController : Controller
811
{
12+
private ToDoContext context;
13+
14+
public int CurrentUserId
15+
{
16+
get { return (int)HttpContext.Items["UserId"]; }
17+
}
18+
19+
public ToDoController(ToDoContext databaseContext)
20+
{
21+
context = databaseContext;
22+
}
23+
924
public JsonResult Get()
1025
{
11-
return Json(new { Test = "response" });
26+
return Json(context.ToDoEntries.Where(o => o.User.Id == CurrentUserId).Select(o => new { o.Id, o.Completed, o.Description, o.Notes, UserId = CurrentUserId }));
1227
}
1328
}
1429
}

0 commit comments

Comments
 (0)