84 Commits

Author SHA1 Message Date
d29486dda9 Merge pull request 'Feature/Auth: last one was authentication, this one is authorization' (#4) from feature/auth into main
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 4s
Build and Deploy Frontend / build-and-deploy (push) Successful in 4s
Reviewed-on: #4
2026-04-23 00:18:39 -05:00
317a7bce9d comments galore
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 6s
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-04-23 00:15:49 -05:00
ef1e9aa759 best of both worlds
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-04-22 23:45:18 -05:00
be183c6fd3 allow removal of self permissions, just not the important one
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-04-22 23:30:25 -05:00
0cda948323 do the same to delete
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 8s
Build and Deploy API / build-and-deploy (push) Successful in 10s
2026-04-22 23:27:31 -05:00
6761ae499b oops wrong http request type
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 7s
2026-04-22 23:23:48 -05:00
b7989a1c2b add api calls to permission modifications
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 9s
2026-04-22 23:21:22 -05:00
42a59c8af3 add debugging frontend for permissions
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 7s
2026-04-22 23:08:33 -05:00
baca04fa03 create permission modification endpoints
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 6s
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-04-22 21:49:15 -05:00
1afa30040d create userdto constructor out of user
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-04-22 21:19:35 -05:00
68685e6398 prevent self user deletion
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-04-22 21:08:02 -05:00
4f60336a37 it was staring me right in the face
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-04-22 20:21:39 -05:00
5f68179fd1 database malarkey
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-04-22 20:14:34 -05:00
37b5dd4637 fix permission table
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 4s
2026-04-22 20:09:20 -05:00
ef1256b38f redo database
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-04-22 20:00:14 -05:00
89942f0731 fix build permission errors
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-04-22 19:55:47 -05:00
9d5bae339e every gosh darn time
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-04-22 19:35:12 -05:00
152db3d99f rework policies to use permissions over roles
Some checks failed
Build and Deploy API / build-and-deploy (push) Failing after 7s
Build and Deploy Frontend / build-and-deploy (push) Successful in 6s
2026-04-22 19:34:55 -05:00
1a0bf385b6 use strings instead of guids
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-04-21 23:22:00 -05:00
5bbe0bfb4d IdentityUsers use Guid instead of int ids
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-04-21 23:17:45 -05:00
60bead4426 seed admin role
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-04-21 22:24:21 -05:00
30214bd212 fix case issues on userName
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 7s
2026-04-21 21:06:52 -05:00
1350284b79 await asyncronous method
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-04-21 21:04:01 -05:00
ffdf997929 add roles to jwt claims
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-04-21 20:32:48 -05:00
500961be07 fix users page
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 5s
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-04-21 20:12:17 -05:00
143d194cdb fix: policy mismatch
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-04-21 19:18:54 -05:00
2f3cb46af3 add roles seeding
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 8s
Build and Deploy API / build-and-deploy (push) Successful in 11s
2026-04-21 19:13:44 -05:00
214f1601b5 comment
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-03-28 00:54:03 -05:00
0af0ddf6b9 i was missing policies oops
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-03-28 00:19:01 -05:00
f271ff59f8 added userDtos
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 7s
Build and Deploy API / build-and-deploy (push) Successful in 10s
2026-03-28 00:01:45 -05:00
5afd9057f2 checkpoint
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 7s
2026-03-27 20:22:17 -05:00
12d1e65ed5 small roles update
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 10s
2026-03-25 23:11:39 -05:00
eeee94d0d6 what da
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-03-24 19:41:48 -05:00
63c2da652c test api roles 2026-03-24 19:41:36 -05:00
e3cd44422c Merge pull request 'Feature/Auth: implement user authentication' (#3) from feature/auth into main
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 4s
Build and Deploy Frontend / build-and-deploy (push) Successful in 4s
Reviewed-on: #3
2026-03-22 20:52:22 -05:00
93e8b6ee0d fix: setting token
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 6s
2026-03-22 20:50:25 -05:00
f1e693cbc0 debug
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 6s
2026-03-22 20:49:27 -05:00
ba7db77505 fix: fix routing based on token validation
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 7s
2026-03-22 20:47:53 -05:00
cd3fad95a5 fix: browser javascript untyped
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 6s
2026-03-22 20:40:53 -05:00
04e2b6acc3 add refresh tokens on client
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 7s
2026-03-22 20:38:49 -05:00
7e02d3cfe1 add logout for refreshTokens
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-03-22 17:25:15 -05:00
74307e614c add refresh tokens
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-03-22 16:48:58 -05:00
31db3bc58c (►__◄)
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 6s
2026-03-22 01:26:53 -05:00
1b32456173 fix: redirect to root after login
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 6s
2026-03-22 01:23:27 -05:00
eb94a1bcb9 re: require authorization for items list
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 7s
Build and Deploy API / build-and-deploy (push) Successful in 10s
2026-03-22 01:21:50 -05:00
10ac1a6076 fix: require authorization for items list
Some checks failed
Build and Deploy API / build-and-deploy (push) Failing after 5s
2026-03-22 01:21:04 -05:00
da6ffa8167 fix item update api
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-03-22 01:17:24 -05:00
89b4398442 revert
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-03-22 01:08:18 -05:00
99ff02b01b fix: item ids
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-03-22 01:00:59 -05:00
67baddf9d0 implement item dtos
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 8s
Build and Deploy API / build-and-deploy (push) Successful in 10s
2026-03-22 00:56:24 -05:00
3d219b8cf7 fix item routes
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 7s
2026-03-21 23:45:52 -05:00
7ab03d8073 change users crud to items
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 8s
Build and Deploy API / build-and-deploy (push) Successful in 10s
2026-03-21 23:44:26 -05:00
a9b4d136d5 Add items crud to api 2026-03-21 20:20:02 -05:00
cda10dfaa4 debug
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 7s
2026-03-21 17:51:02 -05:00
4fe23699c8 fix client to api dtos again
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 7s
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-03-21 17:41:11 -05:00
fc064dd01c add identity to the register endpoint
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-03-21 17:26:50 -05:00
9b4c2062a7 revert database
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-03-21 17:16:17 -05:00
826b654dc9 add another identity migration
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-03-21 16:12:59 -05:00
a3a86d4fde fix entityframework identity dbContext
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-03-21 16:10:53 -05:00
27f3be7761 add another migrtation
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-03-21 15:58:33 -05:00
efde701ba9 i should really test lolcally
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 6s
2026-03-21 15:44:35 -05:00
9645695535 require auth for users list page because itll be easier to test with
Some checks failed
Build and Deploy Frontend / build-and-deploy (push) Failing after 4s
2026-03-21 15:41:54 -05:00
3dd0460209 migrate to identity for authentication
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 12s
2026-03-21 15:38:05 -05:00
ef4f0c0159 fix: dto consistency 2026-03-21 14:13:19 -05:00
817e0b97e6 idk how yaml works apparently
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-03-21 00:23:30 -05:00
cdc8b5c7a4 export secret
Some checks failed
Build and Deploy API / build-and-deploy (push) Failing after 3s
2026-03-21 00:22:31 -05:00
be731be724 yaml syuntax
Some checks failed
Build and Deploy API / build-and-deploy (push) Failing after 8s
2026-03-21 00:20:25 -05:00
9fea2c5b7b properly set environment secret
Some checks failed
Build and Deploy API / build-and-deploy (push) Failing after 7s
2026-03-21 00:16:52 -05:00
f7b537cbed i changed a filename oops
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 4s
2026-03-20 21:09:16 -05:00
109d5f88ea user dtos as strict object templates
Some checks failed
Build and Deploy API / build-and-deploy (push) Failing after 6s
Build and Deploy Frontend / build-and-deploy (push) Successful in 7s
2026-03-20 21:08:32 -05:00
7229e369ae secretize jwt secret
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-03-20 20:52:59 -05:00
a343c2e246 test longer jwt secret
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-03-20 20:11:58 -05:00
ae888d2973 fix non-null register attributes
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-03-20 20:07:25 -05:00
21fad5f698 new migration
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 10s
2026-03-20 20:02:51 -05:00
ce701cd43d ( ˘︹˘ )
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 6s
2026-03-17 22:41:42 -05:00
74200c4575 add the login buttons
Some checks failed
Build and Deploy Frontend / build-and-deploy (push) Failing after 3s
2026-03-17 22:40:22 -05:00
8c86f5ddce literally every time
All checks were successful
Build and Deploy Frontend / build-and-deploy (push) Successful in 6s
2026-03-17 22:31:13 -05:00
661bb03d1d preliminary frontend for ther auth api
Some checks failed
Build and Deploy Frontend / build-and-deploy (push) Failing after 4s
Build and Deploy API / build-and-deploy (push) Successful in 12s
2026-03-17 22:30:59 -05:00
c19cd0c718 add auth migration
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
2026-03-16 21:49:12 -05:00
d8f64754b4 add auth files
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
2026-03-16 21:44:33 -05:00
96026d448f scaffold auth api infrastructure (doesn't work)
Some checks failed
Build and Deploy API / build-and-deploy (push) Failing after 14s
2026-03-16 21:20:54 -05:00
3dfb1ee0a7 Merge branch 'main' of ssh://git.vxbard.net:2222/homeburger/agologum into feature/auth
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 5s
Build and Deploy Frontend / build-and-deploy (push) Successful in 4s
2026-03-15 13:33:06 -05:00
5fe1666163 init 2026-03-15 12:28:03 -05:00
59b5344377 Merge pull request 'feature/client-template' (#2) from feature/client-template into main
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 7s
Build and Deploy Frontend / build-and-deploy (push) Successful in 5s
Reviewed-on: #2
2026-03-14 23:10:46 -05:00
41 changed files with 2171 additions and 293 deletions

6
.env
View File

@@ -2,3 +2,9 @@
sike you thought I was like that
hehehehee (urp so full)
# TODO: should have basic public-safe environment variables here
# then secret environment variables can be added via secrets in the ci script like so:
# job: inject-seccrets $ echo API_KEY={{ secrets.API_KEY }} >> .env
# then they dont have to be inserted by the docker container ( messy)

View File

@@ -39,5 +39,6 @@ jobs:
- name: Deploy container
run: |
export POSTGRES_PASSWORD=${{ secrets.POSTGRES_PASSWORD }}
export JWT_SECRET=${{ secrets.JWT_SECRET }}
docker compose -f ./api/docker-compose.prod.yaml pull agologum-api
docker compose -f ./api/docker-compose.prod.yaml up -d --force-recreate agologum-api

View File

@@ -1,49 +0,0 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace agologum_api.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260314152859_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("agologumApi.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Users");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,36 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace agologum_api.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}
}

View File

@@ -0,0 +1,339 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace agologum_api.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260423011426_InitialMigration")]
partial class InitialMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("RefreshToken", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsRevoked")
.HasColumnType("boolean");
b.Property<string>("Token")
.IsRequired()
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("agologumApi.Models.Item", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("LastEditedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Items");
});
modelBuilder.Entity("agologumApi.Models.User", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.PrimitiveCollection<string>("Permissions")
.HasColumnType("jsonb");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("agologumApi.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("agologumApi.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("agologumApi.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("agologumApi.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,264 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace agologum_api.Migrations
{
/// <inheritdoc />
public partial class InitialMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
Permissions = table.Column<string>(type: "jsonb", nullable: true),
UserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
Email = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(type: "boolean", nullable: false),
PasswordHash = table.Column<string>(type: "text", nullable: true),
SecurityStamp = table.Column<string>(type: "text", nullable: true),
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true),
PhoneNumber = table.Column<string>(type: "text", nullable: true),
PhoneNumberConfirmed = table.Column<bool>(type: "boolean", nullable: false),
TwoFactorEnabled = table.Column<bool>(type: "boolean", nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
LockoutEnabled = table.Column<bool>(type: "boolean", nullable: false),
AccessFailedCount = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Items",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false),
Description = table.Column<string>(type: "text", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
LastEditedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Items", x => x.Id);
});
migrationBuilder.CreateTable(
name: "RefreshTokens",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Token = table.Column<string>(type: "text", nullable: false),
UserId = table.Column<string>(type: "text", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
ExpiresAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
IsRevoked = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RefreshTokens", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
RoleId = table.Column<string>(type: "text", nullable: false),
ClaimType = table.Column<string>(type: "text", nullable: true),
ClaimValue = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserId = table.Column<string>(type: "text", nullable: false),
ClaimType = table.Column<string>(type: "text", nullable: true),
ClaimValue = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(type: "text", nullable: false),
ProviderKey = table.Column<string>(type: "text", nullable: false),
ProviderDisplayName = table.Column<string>(type: "text", nullable: true),
UserId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(type: "text", nullable: false),
RoleId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(type: "text", nullable: false),
LoginProvider = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Value = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "Items");
migrationBuilder.DropTable(
name: "RefreshTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}

View File

@@ -1,4 +1,5 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
@@ -20,7 +21,33 @@ namespace agologum_api.Migrations
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("agologumApi.Models.User", b =>
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@@ -28,17 +55,280 @@ namespace agologum_api.Migrations
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Email")
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("RefreshToken", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsRevoked")
.HasColumnType("boolean");
b.Property<string>("Token")
.IsRequired()
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("agologumApi.Models.Item", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("LastEditedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Users");
b.ToTable("Items");
});
modelBuilder.Entity("agologumApi.Models.User", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.PrimitiveCollection<string>("Permissions")
.HasColumnType("jsonb");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("agologumApi.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("agologumApi.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("agologumApi.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("agologumApi.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}

View File

@@ -1,16 +1,66 @@
// system usings
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System.Text;
// homeburger usings
using agologumApi.Models;
using agologumApi.Services;
var builder = WebApplication.CreateBuilder(args);
// make sure the jwt key exists or else abort, security issue
var key = builder.Configuration["Jwt:Key"];
if(key == null) return;
// connect to the sql database
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddControllers();
// add our services
builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<ItemService>();
builder.Services.AddScoped<JwtService>();
// if this grows sufficiently large we can put elsewhere
// configuration for jwt authentication
builder.Services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders()
.AddRoles<IdentityRole>();
builder.Services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "agologum",
ValidAudience = "agologum",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)),
ClockSkew = TimeSpan.Zero
};
});
// authorization configurations; here's where we register our permissions to policies
// TODO: this suspiciously looks able to be automated through a for loop, only if we can have a static dictionary maybe though?
builder.Services.AddAuthorization(options => {
options.AddPolicy(Permission.SensitiveData_Read, policy =>
policy.RequireClaim("permission", Permission.SensitiveData_Read));
options.AddPolicy(Permission.SensitiveData_Modify, policy =>
policy.RequireClaim("permission", Permission.SensitiveData_Modify));
});
// configuration for behind my nginx proxy
builder.Services.Configure<ForwardedHeadersOptions>(options =>
@@ -27,6 +77,7 @@ builder.Services.Configure<ForwardedHeadersOptions>(options =>
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
// cors; scary needs to be fixed
builder.Services.AddCors(options =>
{
options.AddPolicy("dev",
@@ -35,16 +86,20 @@ builder.Services.AddCors(options =>
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
}); // TODO: scary please fix this
});
// more middleware; probably uncessary at this stage
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// build app
var app = builder.Build();
app.UseForwardedHeaders();
app.UseCors("dev");
app.UseAuthentication();
app.UseAuthorization();
// Configure the HTTP request pipeline.
if (app.Environment.IsEnvironment("Development")) {
@@ -70,6 +125,7 @@ using (var scope = app.Services.CreateScope()) {
Thread.Sleep(5000);
}
}
}
app.Run();

View File

@@ -8,6 +8,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.5" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.5">

View File

@@ -9,5 +9,10 @@
"DefaultConnection": "Host=agologum-net;Port=5432;Database=agologum;Username=agologum;Password=${POSTGRES_PASSWORD}"
},
"AllowedHosts": "*",
"https_port": 443
"https_port": 443,
"Jwt": {
"Key": "",
"Issuer": "agologum-api",
"Audience": "agologum-users"
}
}

View File

@@ -8,6 +8,7 @@ services:
restart: always
environment:
ConnectionStrings__DefaultConnection: Host=agologum-db;Port=5432;Database=agologum;Username=agologum;Password=${POSTGRES_PASSWORD}
Jwt__Key: ${JWT_SECRET} # must export the secret as a variable in the ci script
ports:
- "5000:5000"
networks:

View File

@@ -0,0 +1,137 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using agologumApi.Models;
using agologumApi.Services;
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase {
// identity things
private readonly UserManager<User> userManager_;
private readonly SignInManager<User> signInManager_;
// services
private readonly JwtService jwt_;
private readonly UserService userService_;
// class constructor (where are my initializer lists man)
public AuthController(UserManager<User> userManager, SignInManager<User> signInManager, JwtService jwt, UserService userService) {
userManager_ = userManager;
signInManager_ = signInManager;
jwt_ = jwt;
userService_ = userService;
}
// register endpoint
[HttpPost("register")]
public async Task<ActionResult> Register(RegisterDto dto) {
// create a new user out of the dto from the request
User user = new User {
UserName = dto.UserName,
Email = dto.Email,
CreatedAt = DateTime.UtcNow // yeah why not utc
};
// assigning roles to user. create a user starting with x to give it permissions to read sensitive data
if(dto.UserName.StartsWith("x")) {
user.Permissions = new List<string> { Permission.SensitiveData_Read };
}
// use Identity's user manager to add to db; error check if failed
var result = await userManager_.CreateAsync(user, dto.Password);
if(!result.Succeeded) return BadRequest(result.Errors);
// respond to post as necessary
return CreatedAtAction(
nameof(Register),
new { id = user.Id }
);
}
// login endpoint
[HttpPost("login")]
public async Task<ActionResult> Login(LoginDto dto)
{
// get the user from the database given the username
var user = await userManager_.FindByNameAsync(dto.UserName);
// user not found with that name
if (user == null) return Unauthorized(); // unauthorized instead of not found to not give away info
// use identity's password validation
var result = await signInManager_.CheckPasswordSignInAsync(user, dto.Password, false);
// if failed then youre not real !
if(!result.Succeeded) return Unauthorized();
// login sucess, give you an authentication token
var accessToken = await jwt_.GenerateJwt(user);
var refreshToken = jwt_.GenerateRefreshToken(); // the refresh token is good enough to refresh your access token
RefreshToken newTokenObject = new RefreshToken {
Token = refreshToken,
UserId = user.Id,
CreatedAt = DateTime.UtcNow,
ExpiresAt = DateTime.UtcNow.AddDays(30),
IsRevoked = false
};
await jwt_.AddRefreshToken(newTokenObject);
// the jwt says we trust who you are and can substitute it for login
// contains permissions claims too
// return both access and refresh token
return Ok(new { accessToken, refreshToken });
}
// logout endpoint
[Authorize] // authorize is handled by middleware
[HttpPost("logout")]
public async Task<ActionResult> Logout(string refreshTokenString) {
// revoke refresh token
bool success = await jwt_.RevokeRefreshToken(refreshTokenString);
if(!success) return NotFound();
// frontend refreshes page and detects logout
return Ok();
}
// refresh token endpoint
[HttpPost("refresh")] // allow-anonymous by default
public async Task<ActionResult> Refresh(TokenDto request) {
// reached when the frontend gets an unauthorized response and autoattempts to refresh if available
// get token from request and check if its valid
RefreshToken? storedToken = await jwt_.GetRefreshToken(request.RefreshToken);
if (storedToken == null) return Unauthorized();
bool valid = (storedToken.IsRevoked) ||
(storedToken.ExpiresAt < DateTime.UtcNow);
if(!valid) return Unauthorized(); // TODO: delete the invalid token
// get user from the token and give them new tokens
User? user = await jwt_.GetUser(storedToken.UserId);
if(user == null) return NotFound();
string? newAccessToken = await jwt_.GenerateJwt(user);
if(newAccessToken == null) return NotFound();
string newRefreshToken = jwt_.GenerateRefreshToken();
// construct new token
storedToken.IsRevoked = true;
RefreshToken newTokenObject = new RefreshToken {
Token = newRefreshToken,
UserId = storedToken.UserId,
CreatedAt = DateTime.UtcNow,
ExpiresAt = DateTime.UtcNow.AddDays(30),
IsRevoked = false
};
await jwt_.AddRefreshToken(newTokenObject);
// return new tokens
return Ok(new { accessToken = newAccessToken, refreshToken = newRefreshToken });
}
// TODO
// email verification
// password reset
// oh hell naw 2FA I do not care enough
}

View File

@@ -0,0 +1,76 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using agologumApi.Models;
using agologumApi.Services;
[ApiController]
[Route("api/[controller]")]
public class ItemsController : ControllerBase {
private readonly ItemService service_;
public ItemsController(ItemService service) {
service_ = service;
}
[Authorize]
[HttpGet]
public async Task<ActionResult<List<Item>>> getItems() {
return Ok(await service_.GetAll());
}
[Authorize]
[HttpGet("{id:int}")]
public async Task<ActionResult<Item>> getItem(int id) {
var item = await service_.Get(id);
if (item == null) return NotFound();
return Ok(item);
}
[Authorize] // testing the authorization
[HttpPost]
public async Task<ActionResult<Item>> createItem(ItemDto item) {
Item newItem = new Item {
Name = item.Name,
Description = item.Description,
CreatedAt = DateTime.UtcNow,
LastEditedAt = DateTime.UtcNow
};
var created = await service_.Create(newItem);
return CreatedAtAction(
nameof(getItem),
new { id = created.Id },
created
);
}
[Authorize]
[HttpPut("{id}")]
public async Task<ActionResult<Item>> updateItem(int id, ItemDto item) {
var updated = await service_.Update(id, item);
if (updated == null) return NotFound();
return Ok(updated);
}
[Authorize]
[HttpDelete("{id}")]
public async Task<ActionResult> deleteItem(int id) {
var success = await service_.Delete(id);
if (!success) return NotFound();
return NoContent();
}
}

View File

@@ -1,64 +1,118 @@
// this is basically a demo on roles
// level 0 can't access the users endpoint at all
// level 1 has read permissions
// level 2 has modify permissions
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using agologumApi.Models;
using agologumApi.Services;
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
public class UsersController : ControllerBase {
private readonly UserService service_;
public UsersController(UserService service)
{
public UsersController(UserService service) {
service_ = service;
}
[Authorize(Policy = Permission.SensitiveData_Read)]
[HttpGet]
public async Task<ActionResult<List<User>>> getUsers()
{
return Ok(await service_.GetAll());
public async Task<ActionResult<List<User>>> getUsers() {
List<User> rawArray = await service_.GetAll();
List<UserDto> dtoArray = new List<UserDto>();
foreach(User user in rawArray) {
UserDto newDto = new UserDto(user);
dtoArray.Add(newDto);
}
return Ok(dtoArray);
}
[Authorize(Policy = Permission.SensitiveData_Read)]
[HttpGet("{id:int}")]
public async Task<ActionResult<User>> getUser(int id)
{
var user = await service_.Get(id);
public async Task<ActionResult<User>> getUser(string id) {
var user = await service_.GetById(id);
if (user == null) return NotFound();
return Ok(user);
}
[HttpPost]
public async Task<ActionResult<User>> createUser(User user)
{
var created = await service_.Create(user);
return CreatedAtAction(
nameof(getUser),
new { id = created.Id },
created
);
}
[HttpPut("{id}")]
public async Task<ActionResult<User>> updateUser(int id, User user)
{
var updated = await service_.Update(user);
if (updated == null) return NotFound();
return Ok(updated);
UserDto newDto = new UserDto(user);
return Ok(newDto);
}
[Authorize(Policy = Permission.SensitiveData_Modify)]
[HttpDelete("{id}")]
public async Task<ActionResult> deleteUser(int id)
{
public async Task<ActionResult> deleteUser(string id) {
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if(userId == id) return BadRequest(); // dont allow deletion of yourself
var success = await service_.Delete(id);
if (!success) return NotFound();
return NoContent();
}
[Authorize(Policy = Permission.SensitiveData_Modify)]
[HttpDelete("{id}/{permission}")]
public async Task<ActionResult> removePermission(string id, string permission) {
// get the user this request comes from. since it passed identity auth we can trust it
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if(permission == Permission.SensitiveData_Modify && userId == id) return BadRequest(); // dont allow permission removal of whats allowing us to re-add premissions
// get list of permissions of that user
var user = await service_.GetById(id);
if (user == null) return NotFound();
if(user.Permissions == null) return NotFound();
// verify that the requested permission exists on that user
if(!user.Permissions.Contains(permission)) return NotFound();
// remove the permission from the permission list
user.Permissions.Remove(permission);
// update the user
await service_.Update(id, user);
return NoContent();
}
[Authorize(Policy = Permission.SensitiveData_Modify)]
[HttpPost("{id}/{permission}")] // TODO: this was made with a single button per permission in mind, but may be better as sending an array
public async Task<ActionResult> addPermission(string id, string permission) {
// we'll allow the superuser to elevate their own permissions because they're the superuser
// get list of permissions of the user
var user = await service_.GetById(id);
if (user == null) return NotFound();
if(user.Permissions == null) return NotFound();
// remove add the permission to the user's permission list (if it doesnt already exist)
if(user.Permissions.Contains(permission)) return NoContent();
user.Permissions.Add(permission);
// update the user
await service_.Update(id, user);
return NoContent();
// fyi the user will need to sign out and sign back in so the new permissions are reflected in their jwt claims
// TODO: or on the client i could issue a refresh token request after a permission api call
}
// TODO: add controls on editing roles
}

View File

@@ -2,12 +2,24 @@
using agologumApi.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
public class AppDbContext : DbContext {
public class AppDbContext : IdentityDbContext<User> {
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {
}
public DbSet<User> Users { get; set; }
// Db set for each model besides Users (DbSet<User> is already defined in IdentityDbContext<User>)
public DbSet<Item> Items { get; set; }
public DbSet<RefreshToken> RefreshTokens { get; set; }
protected override void OnModelCreating(ModelBuilder builder) {
base.OnModelCreating(builder);
builder.Entity<User>().Property(u => u.Permissions).HasColumnType("jsonb");
}
}

19
api/src/Models/Item.cs Normal file
View File

@@ -0,0 +1,19 @@
namespace agologumApi.Models;
public class Item {
public int Id { get; set; }
public String Name { get; set; } = "";
public String Description { get; set; } = "";
public DateTime CreatedAt { get; set; }
public DateTime LastEditedAt { get; set; }
};
public class ItemDto {
public String Name { get; set; } = "";
public String Description { get; set; } = "";
}

View File

@@ -0,0 +1,10 @@
// this is a static data model; it doesnt exist in a database (yet)
// lol no dynamic permissions would mean endpoint authorization gates need to be dynamic too
public static class Permission {
public const string SensitiveData_Read = "SensitiveData.Read";
public const string SensitiveData_Modify = "SensitiveData.Modify";
}

View File

@@ -0,0 +1,21 @@
// a refresh token's purpose is to authenticate user's without logging in
public class RefreshToken {
public int Id { get; set; }
public string Token { get; set; } = "";
public string UserId { get; set; } = ""; // in EF Identity the IdentityUser's id is a GUID string (32 hex digits)
public DateTime CreatedAt { get; set; }
public DateTime ExpiresAt { get; set; }
public bool IsRevoked { get; set; }
}
public class TokenDto {
public string RefreshToken { get; set; } = "";
}

View File

@@ -1,10 +1,73 @@
using Microsoft.AspNetCore.Identity;
namespace agologumApi.Models;
public class User {
public class User : IdentityUser {
public int Id { get; set; }
public string Name { get; set; } = "";
public DateTime CreatedAt { get; set; }
// TODO: make this a list of UserPermissions
// where a userpermission has an Id, Permission (string), and userId string
// then we can do something like: get all users with this permission
public List<string>? Permissions { get; set; } = new(); // because this isnt very relational database happy
// properties inherited from IdentityUser:
/*
AccessFailedCount: Gets or sets the number of failed login attempts for the current user.
Claims: Navigation property for the claims this user possesses.
ConcurrencyStamp: A random value that must change whenever a user is persisted to the store
Email: Gets or sets the email address for this user.
EmailConfirmed: Gets or sets a flag indicating if a user has confirmed their email address.
Id: Gets or sets the primary key for this user.
LockoutEnabled: Gets or sets a flag indicating if the user could be locked out.
LockoutEnd: Gets or sets the date and time, in UTC, when any user lockout ends.
Logins: Navigation property for this users login accounts.
NormalizedEmail: Gets or sets the normalized email address for this user.
NormalizedUserName: Gets or sets the normalized user name for this user.
PasswordHash: Gets or sets a salted and hashed representation of the password for this user.
PhoneNumber: Gets or sets a telephone number for the user.
PhoneNumberConfirmed: Gets or sets a flag indicating if a user has confirmed their telephone address.
Roles: Navigation property for the roles this user belongs to.
SecurityStamp: A random value that must change whenever a users credentials change (password changed, login removed)
TwoFactorEnabled: Gets or sets a flag indicating if two factor authentication is enabled for this user.
UserName: Gets or sets the user name for this user.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.entityframeworkcore.identityuser?view=aspnetcore-1.1
*/
};
// DTOs include only the minimum information for transit
public class RegisterDto {
public string UserName { get; set; } = "";
public string Email { get; set; } = "";
public string Password { get; set; } = "";
}
public class LoginDto {
public string UserName { get; set; } = "";
public string Password { get; set; } = "";
}
public class UserDto {
public DateTime CreatedAt { get; set; } = DateTime.UtcNow; // datetimes get compressed to a string
public List<string>? Permissions { get; set; } = [];
public string? Email { get; set; } = "";
public string Id { get; set; } = "";
public string? UserName { get; set; } = "";
// constructor out of a full User object
// REMEMBER: when adding fields to UserDto they must also be set in this constructor or else stuff breaks
public UserDto(User user) {
CreatedAt = user.CreatedAt;
Email = user.Email;
Id = user.Id;
UserName = user.UserName;
Permissions = user.Permissions;
}
};

View File

@@ -0,0 +1,59 @@
using Microsoft.EntityFrameworkCore;
using agologumApi.Models;
namespace agologumApi.Services;
// basic CRUD operations for items in the database
public class ItemService {
private readonly AppDbContext db_;
public ItemService(AppDbContext db) {
db_ = db;
}
public async Task<List<Item>> GetAll() {
return await db_.Items.ToListAsync();
}
public async Task<Item?> Get(int id) {
return await db_.Items.FindAsync(id);
}
public async Task<Item?> Get(string name) {
return await db_.Items.FirstOrDefaultAsync(u => u.Name == name);
}
public async Task<Item> Create(Item item) {
db_.Items.Add(item);
await db_.SaveChangesAsync();
return item;
}
public async Task<Item?> Update(int id, ItemDto item) {
Item? oldItem = await db_.Items.FindAsync(id);
if(oldItem == null) return oldItem;
oldItem.Name = item.Name;
oldItem.Description = item.Description;
oldItem.LastEditedAt = DateTime.UtcNow;
await db_.SaveChangesAsync();
return oldItem;
}
public async Task<bool> Delete(int id) {
Item? item = await db_.Items.FindAsync(id);
if(item != null) {
db_.Items.Remove(item);
await db_.SaveChangesAsync();
return true;
} else {
return false;
}
}
}

View File

@@ -0,0 +1,98 @@
using Microsoft.IdentityModel.Tokens;
using Microsoft.EntityFrameworkCore;
using System.Text;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Identity;
using agologumApi.Models;
public class JwtService {
private readonly IConfiguration config_;
private readonly AppDbContext db_;
private readonly UserManager<User> userManager_;
public JwtService(IConfiguration config, AppDbContext db, UserManager<User> userManager) { // why the heck does c# not have initializer lists ?
config_ = config;
db_ = db;
userManager_ = userManager;
}
// create a jwt string given a user (user contains permissions which go into claims)
public async Task<string?> GenerateJwt(User user) {
// security stuff
string? jwtKey = config_["Jwt:Key"];
if(jwtKey == null) return null;
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
// make sure the user is real
if(user.UserName == null) return null;
// not too sure
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
};
// add each permission that the user has into the claims
List<string>? permissions = user.Permissions;
if(permissions != null) {
foreach(string perm in permissions) {
claims.Add(new Claim("permission", perm));
}
}
// construct that token
var token = new JwtSecurityToken(
issuer: "agologum",
audience: "agologum",
claims: claims,
expires: DateTime.UtcNow.AddHours(2),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
// generating a refresh token is just like a long random password
public string GenerateRefreshToken() {
byte[] randomBytes = new byte[64];
RandomNumberGenerator.Fill(randomBytes.AsSpan());
return Convert.ToBase64String(randomBytes);
}
// we store refresh tokens on our side to check against when a user requests a refresh
public async Task<RefreshToken?> GetRefreshToken(string refreshTokenString) {
return await db_.RefreshTokens.FirstOrDefaultAsync(u => u.Token == refreshTokenString);
}
// add a refresh token to the token db store
public async Task<RefreshToken> AddRefreshToken(RefreshToken refreshToken) {
db_.RefreshTokens.Add(refreshToken);
await db_.SaveChangesAsync();
return refreshToken;
}
// helper to get the User from the id that exists in a refresh token object
public async Task<User?> GetUser(string id) {
return await db_.Users.FindAsync(id);
} // since other places aren't good for having references to db contexts
// remove refresh token from our store; called when user logs out
public async Task<bool> RevokeRefreshToken(string refreshTokenString) {
var refreshToken = await db_.RefreshTokens.FirstOrDefaultAsync(u => u.Token == refreshTokenString);
if(refreshToken == null) return false;
refreshToken.IsRevoked = true;
await db_.SaveChangesAsync();
return true;
}
}

View File

@@ -13,30 +13,26 @@ public class UserService {
db_ = db;
}
// get all users
public async Task<List<User>> GetAll() {
return await db_.Users.ToListAsync();
}
public async Task<User?> Get(int id) {
// get one user with id of id
public async Task<User?> GetById(string id) {
return await db_.Users.FindAsync(id);
}
public async Task<User> Create(User user) {
db_.Users.Add(user);
await db_.SaveChangesAsync();
return user;
// get one user with username of name
public async Task<User?> GetByName(string name) {
return await db_.Users.FirstOrDefaultAsync(u => u.UserName == name);
}
public async Task<User> Update(User user) {
db_.Users.Update(user);
await db_.SaveChangesAsync();
return user;
}
public async Task<bool> Delete(int id) {
User? user = await db_.Users.FindAsync(id);
if(user != null) {
db_.Users.Remove(user);
// delete one user with id of id
public async Task<bool> Delete(string id) {
User? User = await db_.Users.FindAsync(id);
if(User != null) {
db_.Users.Remove(User);
await db_.SaveChangesAsync();
return true;
} else {
@@ -44,4 +40,16 @@ public class UserService {
}
}
// update user of id with user
public async Task<User?> Update(string id, User user) {
User? oldUser = await db_.Users.FindAsync(id);
if(oldUser == null) return oldUser;
oldUser.Permissions = user.Permissions;
await db_.SaveChangesAsync();
return oldUser;
}
}

46
client/src/api/AuthApi.ts Normal file
View File

@@ -0,0 +1,46 @@
// service to interact with the api/auth endpoints
// handles user registration, user logins, tokens, password reset, etc.
import { api, authStorage } from "./axios.ts"
import type { UserDto, RegisterDto, LoginDto } from "../models/User.ts";
const API_URL: string = "/auth";
export const register = async (user: RegisterDto) => {
try {
const response = await api.post(`${API_URL}/register`, user);
return true;
// else return false
} catch (err) {
return false;
}
}
export const login = async (user: LoginDto ) => {
try {
const response = await api.post(`${API_URL}/login`, user);
authStorage.setTokens(response.data);
return true;
} catch (err) {
return false;
}
}
export const logout = () => {
authStorage.clear();
}
export const getToken = () => {
authStorage.getAccessToken();
}

View File

@@ -0,0 +1,18 @@
// services are kinda whatever, but in general its a good idea for all api calls to be within a service (at least thats how angular handles it)
// this item service will handle all to <-> from the server when handling item objects
import api from "./axios.ts"
import type { Item, ItemDto } from "../models/Item.ts";
const API_URL: string = "/items";
export const getItems = () => api.get<Item[]>(`${API_URL}`);
export const getItem = (id: number) => api.get<Item>(`${API_URL}/${id}`);
export const createItem = (data: ItemDto) => api.post<Item>(`${API_URL}`, data);
export const updateItem = (id: number, data: ItemDto) => api.put<Item>(`${API_URL}/${id}`, data);
export const deleteItem = (id: number) => api.delete<Item>(`${API_URL}/${id}`);

View File

@@ -1,25 +1,15 @@
// services are kinda whatever, but in general its a good idea for all api calls to be within a service (at least thats how angular handles it)
// this user service will handle all to <-> from the server when handling user objects
// should be injected with the http client (I think its axios ?)
import axios from "axios";
import type {AxiosResponse } from "axios";
import type { User } from "../models/User.ts";
import api from "./axios.ts"
import type { UserDto } from "../models/User.ts";
const API_URL: string = "/users";
const baseUrl: string = import.meta.env.DEV ? import.meta.env.VITE_DEV_API_URL : "https://app.vxbard.net/api" // TODO: overarching api service
const api = axios.create({
baseURL: baseUrl
});
export const getUsers = () => api.get<UserDto[]>(`${API_URL}`);
export const getUsers = () => api.get<User[]>(`${API_URL}`);
export const getUser = (id: string) => api.get<UserDto>(`${API_URL}/${id}`);
export const getUser = (id: number) => api.get<User>(`${API_URL}/${id}`);
export const deleteUser = (id: string) => api.delete<UserDto>(`${API_URL}/${id}`);
export const createUser = (data: User) => api.post<User>(`${API_URL}`, data);
export const removePermission = (id: string, permission: string) => api.delete(`${API_URL}/${id}/${permission}`)
export const updateUser = (id: number, data: User) => api.put<User>(`${API_URL}/${id}`, data);
export const deleteUser = (id: number) => api.delete<User>(`${API_URL}/${id}`);
export const addPermission = (id: string, permission: string) => api.post(`${API_URL}/${id}/${permission}`)

93
client/src/api/axios.ts Normal file
View File

@@ -0,0 +1,93 @@
// http service hub
// handles interceptors and such
import axios from "axios";
const baseUrl: string = import.meta.env.DEV ? import.meta.env.VITE_DEV_API_URL : "https://app.vxbard.net/api"
export const api = axios.create({
baseURL: baseUrl
});
type FailedRequest = { resolve: (token: string) => void, reject: (error: unknown) => void}
let isRefreshing: boolean = false;
let failedQueue: FailedRequest[] = [];
export const authStorage = {
getAccessToken: () => localStorage.getItem("accessToken"),
getRefreshToken: () => localStorage.getItem("refreshToken"),
setTokens: ({ accessToken, refreshToken } : { accessToken: string, refreshToken: string }) => {
localStorage.setItem("accessToken", accessToken)
localStorage.setItem("refreshToken", refreshToken)
},
clear: () => {
localStorage.removeItem("accessToken")
localStorage.removeItem("refreshToken")
}
}
const processQueue = (error: unknown, token: string | null = null): void => {
failedQueue.forEach(prom => {
if (error) prom.reject(error);
else prom.resolve(token as string);
})
failedQueue = [];
}
// intercept on each request
api.interceptors.request.use(config => { // add access token to request headers
const token = authStorage.getAccessToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// intercept on each response
api.interceptors.response.use(response => response, async error => { // mainly for authentication refreshTokens
const originalRequest = error.config;
// if un authorized then refresh the token
if(error.response?.status === 401 && !originalRequest._retry) {
if(isRefreshing) {
return new Promise((resolve, reject) => {
failedQueue.push({ resolve, reject })
}).then(token => {
originalRequest.headers.Authorization = `Bearer ${token}`;
return api(originalRequest);
}).catch(err => Promise.reject(err));
}
originalRequest._retry = true;
isRefreshing = true;
const refreshToken = authStorage.getRefreshToken();
try {
// request refresh endpoint get back a new accessToken
const res = await axios.post(`${baseUrl}/auth/refresh`, { refreshToken });
const { accessToken, refreshToken: newRefresh } = res.data;
authStorage.setTokens({ accessToken, refreshToken: newRefresh });
processQueue(null, accessToken);
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
return api(originalRequest);
} catch (err) {
processQueue(err, null);
authStorage.clear()
window.location.href = "/login";
return Promise.reject(err);
} finally {
isRefreshing = false;
}
}
return Promise.reject(error);
})
// TODO: if you get a 403 while navigating then redirect to the last authenticated page
// if you gert a 403 on a form submissio nthen do like an unauthorized popup (message: stale session <login link>) (or redirect to login like i said elsewhere)
export default api;

View File

@@ -0,0 +1,33 @@
<script setup lang="ts">
import { onMounted } from "vue";
import { useItemsStore} from "../stores/ItemsStore.ts";
const store = useItemsStore();
onMounted(() => { // register callback for when component is loaded on page
store.fetchItems();
})
</script>
<template>
<div>
<h1>Items</h1>
<router-link to="/item/new">Create Item</router-link>
<table>
<tr v-for="item in store.items" :key="item.id">
<td>{{ item.name }}</td>
<td>
<router-link :to="`/item/${item.id}`">Edit</router-link>
<button @click="store.removeItem(item.id)">Delete</button>
</td>
</tr>
</table>
</div>
</template>

View File

@@ -1,33 +0,0 @@
<script setup lang="ts">
import { onMounted } from "vue";
import { useUsersStore} from "../stores/UsersStore.ts";
const store = useUsersStore();
onMounted(() => { // register callback for when component is loaded on page
store.fetchUsers();
})
</script>
<template>
<div>
<h1>Users</h1>
<router-link to="/user/new">Create User</router-link>
<table>
<tr v-for="user in store.users" :key="user.id">
<td>{{ user.name }}</td>
<td>
<router-link :to="`/user/${user.id}`">Edit</router-link>
<button @click="store.removeUser(user.id)">Delete</button>
</td>
</tr>
</table>
</div>
</template>

13
client/src/models/Item.ts Normal file
View File

@@ -0,0 +1,13 @@
export interface Item {
id: number;
name: string;
description: string;
createdAt: string;
lastEditedAt: string;
}
export interface ItemDto {
name: string;
description: string;
}

View File

@@ -1,8 +1,22 @@
// models are the data objects stored in the database. models defined here must match models defined in api/models
// dtos here must match the the dtos in api/src/Modelts/Dto.cs in name (case insensitive) (types are intermediately serialized to strings)
export interface User {
id: number;
name: string;
email: string
export interface UserDto {
createdAt: string;
email: string;
id: string;
userName: string;
permissions: string;
}
export interface RegisterDto {
userName: string;
email: string;
password: string;
}
export interface LoginDto {
userName: string;
password: string;
}

View File

@@ -0,0 +1,56 @@
<!-- pages/views in vue are basically root-level full-page components -->
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useItemsStore } from "../stores/ItemsStore.ts";
import type { Item } from "../models/Item.ts";
const store = useItemsStore();
const route = useRoute();
const router = useRouter();
const item = ref<Item>({
id: 0,
name: "",
description: "",
createdAt: "",
lastEditedAt: ""
});
const id: string | undefined = route.params.id as string | undefined
onMounted(() => {
if(id) {
const existing = store.items.find(i => i.id == Number(id));
if (existing) item.value = { ...existing };
}
});
async function save(): Promise<void> {
if(id) {
await store.updateItem(Number(id), item.value);
} else {
await store.addItem(item.value);
}
router.push("/items"); // redirect
}
</script>
<template>
<div>
<h2>{{ id ? "Edit Item" : "Create Item" }}</h2> <!-- omg I love ternary operator :D -->
<form @submit.prevent="save">
<input v-model="item.name" placeholder="Name" />
<input v-model="item.description" placeholder="Name" />
<button type="submit">Save</button>
</form>
</div>
</template>

View File

@@ -0,0 +1,44 @@
<script setup lang="ts">
import { onMounted } from "vue"
import { useRoute, useRouter } from "vue-router";
import { useItemsStore } from "../stores/ItemsStore.ts"
import * as authApi from "../api/AuthApi";
const store = useItemsStore()
const router = useRouter();
onMounted(() => {
store.fetchItems()
})
function logout() {
authApi.logout();
router.push("/login");
}
</script>
<template>
<div>
<h1>Items</h1>
<router-link to="/item/new">Create Item</router-link>
<table>
<tr v-for="item in store.items" :key="item.id">
<td>{{ item.name }}</td>
<td>
<router-link :to="`/item/${item.id}`" custom v-slot="{ navigate }">
<button @click="navigate" role="link">Edit</button>
</router-link>
<button @click="store.removeItem(item.id)">Delete</button>
</td>
</tr>
</table>
<button @click="logout()">Logout</button>
</div>
</template>

View File

@@ -0,0 +1,50 @@
<script setup lang="ts">
import { onMounted, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import type { LoginDto } from "../models/User.ts";
import * as authApi from "../api/AuthApi";
const router = useRouter();
const user = reactive<LoginDto>({ // the template ensures type consistency
userName: "",
password: "",
});
onMounted(() => {
});
async function login(): Promise<void> {
const success: boolean = await authApi.login(user);
if(success) {
router.push("/"); // redirect
} else {
// prompt try again
}
// TODO: interceptor for when a request returns unauthorized to redirect to login
// TODO: when redirected to login, save previous url as a query parameter then redirect back to that url after login
}
</script>
<template>
<div>
<h2>Login</h2>
<form @submit.prevent="login">
<input v-model="user.userName" placeholder="username" />
<input v-model="user.password" type="password" placeholder="password" />
<button type="submit">Submit</button>
</form>
</div>
</template>

View File

@@ -0,0 +1,51 @@
<script setup lang="ts">
import { onMounted, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import type { RegisterDto } from "../models/User.ts";
import * as authApi from "../api/AuthApi";
const router = useRouter();
const user = reactive<RegisterDto>({ // the template ensures type consistency
userName: "",
email: "",
password: "",
});
onMounted(() => {
});
async function register(): Promise<void> {
const success: boolean = await authApi.register(user);
if(success) {
router.push("/login"); // redirect
} else {
// prompt try again
}
}
</script>
<template>
<div>
<h2>Register</h2>
<form @submit.prevent="register">
<input v-model="user.userName" placeholder="username" />
<input v-model="user.email" placeholder="email" />
<input v-model="user.password" placeholder="password" />
<button type="submit">Submit</button>
</form>
</div>
</template>

View File

@@ -1,54 +0,0 @@
<!-- pages/views in vue are basically root-level full-page components -->
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useUsersStore } from "../stores/UsersStore.ts";
import type { User } from "../models/User.ts";
const store = useUsersStore();
const route = useRoute();
const router = useRouter();
const user = ref<User>({
name: "",
id: 0,
email: "",
});
const id: string | undefined = route.params.id as string | undefined
onMounted(() => {
if(id) {
const existing = store.users.find(i => i.id == Number(id));
if (existing) user.value = { ...existing };
}
});
async function save(): Promise<void> {
if(id) {
await store.updateUser(Number(id), user.value);
} else {
await store.addUser(user.value);
}
router.push("/users"); // redirect
}
</script>
<template>
<div>
<h2>{{ id ? "Edit User" : "Create User" }}</h2> <!-- omg I love ternary operator :D -->
<form @submit.prevent="save">
<input v-model="user.name" placeholder="Name" />
<button type="submit">Save</button>
</form>
</div>
</template>

View File

@@ -1,35 +1,55 @@
<script setup lang="ts">
import { onMounted } from "vue"
import { onMounted, reactive } from "vue"
import { useRoute, useRouter } from "vue-router";
import { useUsersStore } from "../stores/UsersStore.ts"
import * as authApi from "../api/AuthApi";
const store = useUsersStore()
const router = useRouter();
onMounted(() => {
store.fetchUsers()
})
function logout() {
authApi.logout();
router.push("/login");
}
const inputs = reactive<Record<number, string>>({});
store.users.forEach((_, i) => {
inputs[i] = ""
});
const addPermission = (userId: string, index: number) => {
if(inputs[index] != null) store.addPermission(userId, inputs[index]);
}
</script>
<template>
<div>
<h1>Users</h1>
<router-link to="/user/new">Create User</router-link>
<table>
<tr v-for="user in store.users" :key="user.id">
<td>{{ user.name }}</td>
<tr v-for="(user, index) in store.users" :key="user.id">
<td>{{ user.userName }}</td>
<td>
<router-link :to="`/user/${user.id}`" custom v-slot="{ navigate }">
<button @click="navigate" role="link">Edit</button>
</router-link>
<button @click="store.removeUser(user.id)">Delete</button>
</td>
<td v-for="perm in user.permissions" :key="user.id">
<button @click="store.removePermission(user.id, perm)">Remove {{ perm }} permission</button>
</td>
<td>
<form @submit.prevent="addPermission(user.id, index)">
<input type="text" v-model="inputs[index]" placeholder="permission" />
<button type="submit">Add Permission</button>
</form>
</td>
</tr>
</table>
<button @click="logout()">Logout</button>
</div>
</template>

View File

@@ -10,7 +10,21 @@
<h3>yeah im so cool rn</h3>
<h1>imagining what I could do with themes :o</h1>
<h3>TODO: if(logged in) show this stuff; else dont.</h3>
<router-link to="/items" custom v-slot="{ navigate }">
<button @click="navigate" role="link">Items</button>
</router-link>
<router-link to="/users" custom v-slot="{ navigate }">
<button @click="navigate" role="link">Users</button>
</router-link>
<router-link to="/register" custom v-slot="{ navigate }"> <!-- TODO: only if token == invalid -->
<button @click="navigate" role="link">Register</button>
</router-link>
<router-link to="/login" custom v-slot="{ navigate }"> <!-- TODO: only if token == invalid -->
<button @click="navigate" role="link">Login</button>
</router-link>
</template>

View File

@@ -2,16 +2,24 @@
// the router creates front-end endpoints and serves pages to them
import { createRouter, createWebHistory } from "vue-router";
import LoginForm from "../pages/LoginForm.vue";
import RegisterForm from "../pages/RegisterForm.vue";
import ItemsList from "../pages/ItemsList.vue";
import ItemForm from "../pages/ItemForm.vue";
import UsersList from "../pages/UsersList.vue";
import UserForm from "../pages/UserForm.vue";
import index from "../pages/index.vue";
import { authStorage } from "../api/axios.ts"
// link path to the page component
const routes = [
{ path: "/", component: index },
{ path: "/users", component: UsersList },
{ path: "/user/new", component: UserForm },
{ path: "/user/:id", component: UserForm }
{ path: "/login", component: LoginForm },
{ path: "/register", component: RegisterForm },
{ path: "/items", component: ItemsList, meta: { requiresAuth: true } },
{ path: "/item/new", component: ItemForm, meta: { requiresAuth: true } },
{ path: "/item/:id", component: ItemForm, meta: { requiresAuth: true } },
{ path: "/users", component: UsersList, meta: { requiresAuth: true } }
]; // I really like this
const router = createRouter({
@@ -19,4 +27,17 @@ const router = createRouter({
routes: routes,
});
// intercept before routing
router.beforeEach((to, from, next) => {
const token: string | null = authStorage.getAccessToken();
if(to.meta.requiresAuth && !token) { // if the page requires use to be signed in, they must have at least a token set
next("/login");
} else {
next();
}
});
// if the api responds unauthorized (401) then it also will auto-redirect to the login page
export default router;

View File

@@ -0,0 +1,48 @@
// stores are for component state management
// Pinia (?) i kinda dont get it because in angular you just hook a component to a service and that's it,
// though I guess the service handled the state management
// sighh
import { defineStore } from "pinia";
import type { Item, ItemDto } from "../models/Item.ts";
import * as itemsApi from "../api/ItemsApi";
interface ItemState {
items: Item[];
loading: boolean;
}
export const useItemsStore = defineStore("items", {
state: (): ItemState => ({
items: [],
loading: false
}),
actions: {
async fetchItems() {
this.loading = true;
const response = await itemsApi.getItems();
this.items = response.data;
this.loading = false;
},
async addItem(item: ItemDto) {
const response = await itemsApi.createItem(item);
this.items.push(response.data);
},
async updateItem(id: number, item: ItemDto) {
const response = await itemsApi.updateItem(id, item);
const index = this.items.findIndex(i => i.id === id);
this.items[index] = response.data;
},
async removeItem(id: number) {
await itemsApi.deleteItem(id);
this.items = this.items.filter(i => i.id !== id);
}
}
});

View File

@@ -1,15 +1,10 @@
// stores are for component state management
// Pinia (?) i kinda dont get it because in angular you just hook a component to a service and that's it,
// though I guess the service handled the state management
// sighh
import { defineStore } from "pinia";
import type { User } from "../models/User.ts";
import * as api from "../api/UsersApi";
import type { UserDto } from "../models/User.ts";
import * as usersApi from "../api/UsersApi";
interface UserState {
users: User[];
users: UserDto[];
loading: boolean;
}
@@ -23,25 +18,22 @@ export const useUsersStore = defineStore("users", {
actions: {
async fetchUsers() {
this.loading = true;
const response = await api.getUsers();
const response = await usersApi.getUsers();
this.users = response.data;
this.loading = false;
},
async addUser(user: User) {
const response = await api.createUser(user);
this.users.push(response.data);
},
async updateUser(id: number, user: User) {
await api.updateUser(id, user);
const index = this.users.findIndex(i => i.id === id);
this.users[index] = user;
},
async removeUser(id: number) {
await api.deleteUser(id);
async removeUser(id: string) {
await usersApi.deleteUser(id);
this.users = this.users.filter(i => i.id !== id);
},
async removePermission(id: string, permission: string) {
await usersApi.removePermission(id, permission);
},
async addPermission(id: string, permission: string) {
await usersApi.addPermission(id, permission);
}
}

25
scripts/DEV_README.md Normal file
View File

@@ -0,0 +1,25 @@
## These are some notes for development
# contains some helpful tips, commands, and knowledge
Resetting the database (for dev):
> set development evironment (specify non-docker network and db password)
> dotnet ef database drop
> dotnet ef migrations remove
> if above errors, dotnet ef database update 0
> dotnet ef migrations add InitialCreate
To see live logs:
sudo docker logs -f -t agologum-api
public user:
> username=bard (admin)
> username=xvbard (superuser)
> password=Public*890
chrome dev tools troubleshooting
> response body: Network => url endpoint => Response => expand
Always test build before committing
> for the client: $ npm run dev
> for the api: $ dotnet build