Compare commits

..

44 Commits

Author SHA1 Message Date
Paul Schneider 39f98229eb WIP Accesses 7 months ago
Paul Schneider bc803b1547 Maps controller routes 7 months ago
Paul Schneider 834866663a Inits the workflow configuration 7 months ago
Paul Schneider 70d24e17d8 Identity Server reference 7 months ago
Paul Schneider 848d1a9ddf Sdk version bump to net8.0 7 months ago
Paul Schneider 87d2e85f70 comleting the migration to net 7.0 1 year ago
Paul Schneider 6bc5c647a0 update 1 year ago
Paul Schneider 64babca37b render pages 1 year ago
Paul Schneider 16b7d97c75 asciidoc tag 1 year ago
Paul Schneider 921a16d471 help the tags 1 year ago
Paul Schneider 1d3f2c303d use asciidocnet 1 year ago
Paul Schneider 58076d4e7b layout & style 1 year ago
Paul Schneider b46c4b3447 Got a login 1 year ago
Paul Schneider 908d461552 cleanup 1 year ago
Paul Schneider 02d80795ca a blog index 1 year ago
Paul Schneider 2562c9a569 Got a profile 1 year ago
Paul Schneider 86aebbdc9c updated 2 years ago
Paul Schneider d1ddade1a0 subbanner is optional 2 years ago
Paul Schneider 2cc196225a a layout 2 years ago
Paul Schneider a2009e41aa more references 2 years ago
Paul Schneider 76224cda73 a first rendering 2 years ago
Paul Schneider 42dba1b6c1 a migration 2 years ago
Paul Schneider efcb1620d6 migration applied 2 years ago
Paul Schneider ff2a72f112 a Startup 2 years ago
Paul Schneider c4b7a5c48d Builds. 2 years ago
Paul Schneider ae4de6bab7 18 left 2 years ago
Paul Schneider 4d9c285700 50 left 2 years ago
Paul Schneider 64febe48b0 97 remaining 2 years ago
Paul Schneider c81f974ade 309 remainging 2 years ago
Paul Schneider e1812737bd FIXME Razor page errors 2 years ago
Paul Schneider 8b607e2606 FIXME SR is private 2 years ago
Paul Schneider dac93a6206 got the server lib 2 years ago
Paul Schneider 6fe0dad775 got Abstraction 2 years ago
Paul Schneider ca9af3f5a0 Code quality 2 years ago
Paul Schneider 00d1e3bdc4 no 80 3 years ago
Paul Schneider 610b5575a4 no 80 3 years ago
Paul Schneider e02e4b3734 no 80 3 years ago
Paul Schneider dabcca1517 no 80 3 years ago
Paul Schneider deb5d1965b no 80 3 years ago
Paul Schneider 7e280e7804 version bump 3 years ago
Paul Schneider 3f8e74cdf6 Version 1.0.8 3 years ago
Paul Schneider ea44c7e621 Compatible 3 years ago
Paul Schneider 855236d528 site css updated 3 years ago
Paul Schneider fd5ab73439 Was breaking the build 3 years ago
2184 changed files with 575709 additions and 16221 deletions

7
.gitignore vendored

@ -7,7 +7,7 @@
.paket/ .paket/
.vscode/ .vscode/
.vs/ .vs/
.dnx/ .sass-cache/
bin bin
obj obj
@ -21,6 +21,8 @@ RSA-Params.json
appsettings.*.json appsettings.*.json
omnisharp.json omnisharp.json
DataProtection/
/packages/ /packages/
/src/Yavsc/Avatars-*/ /src/Yavsc/Avatars-*/
/src/Yavsc/Blog-*/ /src/Yavsc/Blog-*/
@ -29,7 +31,7 @@ omnisharp.json
/src/Yavsc/Temp-*/ /src/Yavsc/Temp-*/
/src/Yavsc/*-Avatars/ /src/Yavsc/*-Avatars/
/src/Yavsc/bower_components/ /src/Yavsc/bower_components/
/src/Yavsc/AppData*/ /src/Yavsc/Data-Dev/
/src/test/testingrepo/ /src/test/testingrepo/
connectionsettings.Development.json connectionsettings.Development.json
appsettings.Development.json appsettings.Development.json
@ -40,3 +42,4 @@ builds/
/test/yavscTests/test-results.html /test/yavscTests/test-results.html
/binaries/Debug/yavscd /binaries/Debug/yavscd
yavsc-pre yavsc-pre

@ -8,7 +8,7 @@ In this doc, let's say, `FreeField`
### A domain name ### A domain name
Wait ... `freefield.pschneider.fr` Wait ... `pschneider.fr`
You'll have to see with your provider, in order to power it, and make it point to your host ip, at least concerning the ports 80 & 443. You'll have to see with your provider, in order to power it, and make it point to your host ip, at least concerning the ports 80 & 443.
### An Npgsql db ### An Npgsql db

@ -2,7 +2,7 @@
MONO_PREFIX=/home/paul/mono46 MONO_PREFIX=/home/paul/mono46
DNX_USER_HOME=/home/paul/.dnx DNX_USER_HOME=/home/paul/.dnx
DNXLIBS=Microsoft.Dnx.Host.Mono.dll Microsoft.Dnx.Host.dll Microsoft.Dnx.ApplicationHost.dll Microsoft.Dnx.Loader.dll Microsoft.Dnx.Compilation.Abstractions.dll Microsoft.Dnx.Compilation.CSharp.Abstractions.dll Microsoft.CodeAnalysis.dll Microsoft.CodeAnalysis.CSharp.dll Microsoft.Dnx.Compilation.CSharp.Common.dll Microsoft.Dnx.Compilation.CSharp.dll Microsoft.Dnx.Compilation.dll Microsoft.Dnx.Runtime.dll Microsoft.Dnx.Runtime.Internals.dll Microsoft.Extensions.PlatformAbstractions.dll System.Collections.Immutable.dll System.Reflection.Metadata.dll DNXLIBS=Microsoft.Dnx.Host.Mono.dll Microsoft.Dnx.Host.dll Microsoft.Dnx.ApplicationHost.dll Microsoft.Dnx.Loader.dll Microsoft.Dnx.Compilation.Abstractions.dll Microsoft.Dnx.Compilation.CSharp.Abstractions.dll Microsoft.CodeAnalysis.dll Microsoft.CodeAnalysis.CSharp.dll Microsoft.Dnx.Compilation.CSharp.Common.dll Microsoft.Dnx.Compilation.CSharp.dll Microsoft.Dnx.Compilation.dll Microsoft.Dnx.Runtime.dll Microsoft.Dnx.Runtime.Internals.dll Microsoft.Extensions.PlatformAbstractions.dll System.Collections.Immutable.dll System.Reflection.Metadata.dll
DNXLIBFP:=$(addprefix $(DNX_USER_HOME)/runtimes/dnx-mono.1.0.0-rc1-update2/bin/, $(DNXLIBS)) DNXLIBFP:=./packages/System.Diagnostics.DiagnosticSource/4.0.0-beta-23516/lib/portable-net45+win8+wp8+wpa81/System.Diagnostics.DiagnosticSource.dll $(addprefix $(DNX_USER_HOME)/runtimes/dnx-mono.1.0.0-rc1-update2/bin/, $(DNXLIBS))
CONFIG=Debug CONFIG=Debug
yavscd=yavscd yavscd=yavscd
@ -79,7 +79,7 @@ yavscassemblies: src/Yavsc/bin/$(CONFIG)/dnx451/Yavsc.dll src/Yavsc.Server/bin/$
yavscd: yavscassemblies updatedeps yavscd: yavscassemblies updatedeps
mkdir -p binaries/$(CONFIG) mkdir -p binaries/$(CONFIG)
mkbundle --static $(DNXLIBS) src/Yavsc/bin/$(CONFIG)/dnx451/Yavsc.dll src/Yavsc/bin/$(CONFIG)/dnx451/pt/Yavsc.resources.dll src/Yavsc/bin/$(CONFIG)/dnx451/en/Yavsc.resources.dll src/Yavsc.Server/bin/$(CONFIG)/dnx451/Yavsc.Server.dll src/Yavsc.Server/bin/$(CONFIG)/dnx451/en/Yavsc.Server.resources.dll src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/Yavsc.Abstract.dll src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/en/Yavsc.Abstract.resources.dll src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/pt/Yavsc.Abstract.resources.dll src/OAuth.AspNet.AuthServer/bin/$(CONFIG)/dnx451/OAuth.AspNet.AuthServer.dll src/OAuth.AspNet.Token/bin/$(CONFIG)/dnx451/OAuth.AspNet.Token.dll $(shell ls private/lib/*.dll) -L $(DNX_USER_HOME)/runtimes/dnx-mono.1.0.0-rc1-update2/bin --machine-config $(MONO_PREFIX)/etc/mono/4.5/machine.config -o $(yavscd) mkbundle --deps $(DNXLIBS) src/Yavsc/bin/$(CONFIG)/dnx451/Yavsc.dll src/Yavsc/bin/$(CONFIG)/dnx451/pt/Yavsc.resources.dll src/Yavsc/bin/$(CONFIG)/dnx451/en/Yavsc.resources.dll src/Yavsc.Server/bin/$(CONFIG)/dnx451/Yavsc.Server.dll src/Yavsc.Server/bin/$(CONFIG)/dnx451/en/Yavsc.Server.resources.dll src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/Yavsc.Abstract.dll src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/en/Yavsc.Abstract.resources.dll src/Yavsc.Abstract/bin/$(CONFIG)/dnx451/pt/Yavsc.Abstract.resources.dll src/OAuth.AspNet.AuthServer/bin/$(CONFIG)/dnx451/OAuth.AspNet.AuthServer.dll src/OAuth.AspNet.Token/bin/$(CONFIG)/dnx451/OAuth.AspNet.Token.dll $(shell ls private/lib/*.dll) -L $(DNX_USER_HOME)/runtimes/dnx-mono.1.0.0-rc1-update2/bin --machine-config $(MONO_PREFIX)/etc/mono/4.5/machine.config -o $(yavscd)
strip_yavscd: $(yavscd) strip_yavscd: $(yavscd)
strip $(yavscd) strip $(yavscd)

@ -11,56 +11,21 @@ C'est une application mettant en oeuvre une prise de contact entre un demandeur
## Construction ## Construction
Le code est du c sharp, dont les librairies sont restorées et le tout compilé avec les librairies DNX de M$, téléchargeable en executant le script d'installation suivant (c.f. `/.travis.yml`):
```bash
curl --insecure -sSL https://lua.pschneider.fr/files/Paul/dnx-install.sh | bash && DNX_USER_HOME=`pwd -P`/dnx . ./dnx/dnvm/dnvm.sh && cd Yavsc && dnu restore
```
Une fois l'environnement ainsi pollué, executer, depuis le sous dossier `Yavsc`:
```bash ```bash
dnu build dotnet build
```
L'utilisation du serveur web, avec un runtime Mono, échoura dans ses version récentes (à peu près supérieure ou égale à 4.7).
La version 4.6.2 de mono convient:
```
[monoperso] ~/workspace/yavsc/Yavsc @ mono --version
Mono JIT compiler version 4.6.2 (Stable 4.6.2.7/08fd525 jeudi 18 janvier 2018, 13:10:54 (UTC+0100))
TLS: __thread
SIGSEGV: altstack
Notifications: epoll
Architecture: amd64
Disabled: none
Misc: softdebug
LLVM: supported, not enabled.
GC: sgen
``` ```
et, pour execution en environement de développement et, pour execution en environement de développement
``` ```
[monoperso] ~/workspace/yavsc/Yavsc @ ASPNET_ENV=Development dnx web ~/workspace/yavsc/Yavsc @ ASPNETCORE_ENV=Development dotnet run
warn: Yavsc.Startup[0]
AppData was not found in environment variables
warn: Yavsc.Startup[0]
It has been set to : /home/paul/workspace/yavsc/Yavsc/AppDataDevelopment
Hosting environment: Development
Now listening on: http://*:5000
Application started. Press Ctrl+C to shut down.
``` ```
Si vous êtes arrivé jusqu'ici, vous devriez pouvoir visiter la home page :
<http://localhost:5000>.
## Tests ## Tests
Utilisez GNU/Makefile (et visitez le code, dans le dossier `test` ): Utilisez GNU/Makefile (et visitez le code, dans le dossier `test` ):
Depuis le répertoire racine: [TOREDO] Depuis le répertoire racine:
```bash ```bash
make test make test
@ -72,21 +37,6 @@ make test
[TODO] [TODO]
### la configuration Apache 2
[TODO]
### la mise en pré-production
Pour déployer le tout en production, on peut d'abord déployer en "pré-production",
Afin de pouvoir tester manuellement quelque dernier développement :
```bash
cd Yavsc
make pushInPre # arrete kestrel-pre, pousse tout dans DESTDIR=/srv/www/yavscpre avec rsync,
# et redemarre kestrel-pre
```
### La Prod ### La Prod
Une fois sûr de vous, et une fois que Git dit propre votre copie de travail, depuis le répertoire `Yavsc`, lancez `make pushInProd`. Une fois sûr de vous, et une fois que Git dit propre votre copie de travail, depuis le répertoire `Yavsc`, lancez `make pushInProd`.

@ -7,4 +7,4 @@
| ------- | ------------------ | | ------- | ------------------ |
| 1.0.6 | :x: | | 1.0.6 | :x: |
(https://yavsc.pschneider.fr) (https://pschneider.fr:84)

@ -6,7 +6,6 @@ Ceci est une grosse liste de fonctionnalités, existantes, ou à implémenter, o
## Jalon 1 ## Jalon 1
☐ Redirection vers la Page d'accueil à la validation du second facteur (evitera l'erreur Anti-forgery token)
☐ Des spécifications détaillées du coeur de l'application ☐ Des spécifications détaillées du coeur de l'application
✔ Acces (publique) aux Blogs. @done (August 13th 2016, 0:51) ✔ Acces (publique) aux Blogs. @done (August 13th 2016, 0:51)
✔ Accès aux profiles des intervenants. @done (August 13th 2016, 0:57) ✔ Accès aux profiles des intervenants. @done (August 13th 2016, 0:57)

Binary file not shown.

@ -1,131 +0,0 @@
#!/bin/bash
### BEGIN INIT INFO
# Provides: kestrel
# Required-Start: $local_fs $network $named $time $syslog $postgresql
# Required-Stop: $local_fs $network $named $time $syslog $postgresql
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: Script to run asp.net 5 application in background
### END INIT INFO
# Author: Ivan Derevianko aka druss <drussilla7@gmail.com>
# Modified by: Paul Schneider <redienhcs.luap@gmail.com>
. /lib/init/vars.sh
. /lib/lsb/init-functions
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
CONFIGS="/etc/kestrel/*.webenv"
TMP_SAVE_runlevel_VAR=$runlevel
unset runlevel
running() {
if [ -f $PIDFILE ]
then
PID=$(cat $PIDFILE)
if kill -0 $PID 2>/dev/null
then
return 0
fi
fi
return 1
}
setdnxenv() {
env=$1
. $env
# reset all except the name to default values
export ASPNET_ENV=$NAME
export WWW_USER=www-data
YAVSCBIN=/usr/local/bin/yavscd
PROJECT=approot/Web
CONFIGURATION=Release
ROOT=/srv/www/yavsc
DESC="$NAME"
PIDFILE=/var/run/kestrel-${NAME}.pid
LOGDIR=/var/log
# reset to specified values
. $env
}
status() {
for env in $CONFIGS
do
setdnxenv "$env"
if running;
then
echo "Service running $DESC ($NAME; pid: $PID)"
else
echo "Service stopped $DESC ($NAME)"
fi
done
}
start() {
# wait a little for postgresql to be available
sleep 1
for env in $CONFIGS
do
setdnxenv "$env"
if running; then
echo "Service already running $DESC" "$NAME"
log_end_msg 0
else
log_daemon_msg "Starting service $NAME for user $WWW_USER"
if ! start-stop-daemon -SbmCv -u $WWW_USER -p $PIDFILE -d $ROOT -g www-data -x $YAVSCBIN -- --project $PROJECT --configuration $CONFIGURATION $NAME > "${LOGDIR}/kestrel-${NAME}.log"
then
log_daemon_msg "Could not start $NAME : $?, see ${LOGDIR}/kestrel-${NAME}.log"
log_end_msg 2
else
log_daemon_msg "Service $DESC started ($NAME), logs: ${LOGDIR}/kestrel-${NAME}.log"
log_end_msg 0
fi
fi
done
}
stop() {
for env in $CONFIGS
do
setdnxenv "$env"
if running
then
log_daemon_msg "Stopping service $NAME"
start-stop-daemon -K -p "$PIDFILE"
log_daemon_msg "$DESC stopped"
log_end_msg 0
else
log_daemon_msg "$DESC Service not running"
log_end_msg 1
fi
done
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
sleep 1
start
;;
status)
status
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
export runlevel=$TMP_SAVE_runlevel_VAR

@ -1,11 +1,11 @@
#!/bin/bash #!/bin/bash
### BEGIN INIT INFO ### BEGIN INIT INFO
# Provides: kestrel-pre # Provides: yavsc
# Required-Start: $local_fs $network $named $time $syslog $postgresql # Required-Start: $local_fs $network $named $time $syslog $postgresql
# Required-Stop: $local_fs $network $named $time $syslog $postgresql # Required-Stop: $local_fs $network $named $time $syslog $postgresql
# Default-Start: 2 3 4 5 # Default-Start: 2 3 4 5
# Default-Stop: 0 1 6 # Default-Stop: 0 1 6
# Description: Script to run asp.net 5 application in background # Description: Script to run yavsc
### END INIT INFO ### END INIT INFO
# Author: Ivan Derevianko aka druss <drussilla7@gmail.com> # Author: Ivan Derevianko aka druss <drussilla7@gmail.com>
@ -14,8 +14,9 @@
. /lib/init/vars.sh . /lib/init/vars.sh
. /lib/lsb/init-functions . /lib/lsb/init-functions
NAME=yavsc
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
CONFIGS="/etc/kestrel/*.prewebenv"
TMP_SAVE_runlevel_VAR=$runlevel TMP_SAVE_runlevel_VAR=$runlevel
unset runlevel unset runlevel
@ -33,47 +34,34 @@ running() {
} }
setdnxenv() { export WWW_USER=www-data
env=$1 export ROOT=/srv/www/${NAME}
. $env export DESC="$NAME"
# reset all except the name to default values export PIDFILE=/var/run/kestrel-${NAME}.pid
export ASPNET_ENV=$NAME export LOGDIR=/var/log
export WWW_USER=www-data export DOTNET_CLI_HOME=$ROOT
YAVSCBIN=/usr/local/bin/yavscd-pre export ASPDOTNETCORE_ENVIRONMENT=Production
PROJECT=approot/Web export ASPDOTNETCORE_LOGLEVEL=Information
CONFIGURATION=Release
ROOT=/srv/www/yavscpre
DESC="$NAME"
PIDFILE=/var/run/kestrel-${NAME}.pid
LOGDIR=/var/log
# reset to specified values
. $env
}
status() { status() {
for env in $CONFIGS
do
setdnxenv "$env"
if running; if running;
then then
echo "Service running $DESC ($NAME; pid: $PID)" echo "Service running $DESC ($NAME; pid: $PID)"
else else
echo "Service stopped $DESC ($NAME)" echo "Service stopped $DESC ($NAME)"
fi fi
done echo WWW_USER: $WWW_USER ROOT:$ROOT DESC: $DESC NAME: $NAME PIDFILE: $PIDFILE LOGDIR=$LOGDIR
} }
start() { start() {
for env in $CONFIGS
do
setdnxenv "$env"
if running; then if running; then
echo "Service already running $DESC" "$NAME" echo "Service already running $DESC" "$NAME"
log_end_msg 0 log_end_msg 0
else else
cd $ROOT
sleep 4
log_daemon_msg "Starting service $NAME for user $WWW_USER" log_daemon_msg "Starting service $NAME for user $WWW_USER"
if ! start-stop-daemon -SbmCv -u $WWW_USER -p $PIDFILE -d $ROOT -g www-data -x $YAVSCBIN -- --project $PROJECT --configuration $CONFIGURATION $NAME > "${LOGDIR}/kestrel-${NAME}.log" if ! start-stop-daemon -SbmCv -u $WWW_USER -p $PIDFILE -d $ROOT -g www-data -x yavsc > "${LOGDIR}/kestrel-${NAME}.log"
then then
log_daemon_msg "Could not start $NAME : $?, see ${LOGDIR}/kestrel-${NAME}.log" log_daemon_msg "Could not start $NAME : $?, see ${LOGDIR}/kestrel-${NAME}.log"
log_end_msg 2 log_end_msg 2
@ -82,14 +70,10 @@ start() {
log_end_msg 0 log_end_msg 0
fi fi
fi fi
done
} }
stop() { stop() {
for env in $CONFIGS
do
setdnxenv "$env"
if running if running
then then
log_daemon_msg "Stopping service $NAME" log_daemon_msg "Stopping service $NAME"
@ -100,7 +84,6 @@ stop() {
log_daemon_msg "$DESC Service not running" log_daemon_msg "$DESC Service not running"
log_end_msg 1 log_end_msg 1
fi fi
done
} }
@ -113,7 +96,6 @@ case "$1" in
;; ;;
restart) restart)
stop stop
sleep 1
start start
;; ;;
status) status)

@ -4,5 +4,10 @@
"scripts", "scripts",
"tests" "tests"
], ],
"sdk": {
"version": "8.0.200",
"runtime": "dotnet",
"architecture": "x64"
},
"packages": "packages" "packages": "packages"
} }

@ -3,12 +3,10 @@
"enabled": false "enabled": false
}, },
"msbuild": { "msbuild": {
"enabled": false "enabled": true
}, },
"Dnx": { "Dnx": {
"enabled": true, "enabled": false
"enablePackageRestore": false,
"projects": "src/*/project.json;*/project.json;project.json;test/*/project.json"
}, },
"Script": { "Script": {
"enabled": false "enabled": false
@ -21,5 +19,4 @@
], ],
"userExcludeSearchPatterns": [] "userExcludeSearchPatterns": []
} }
} }

@ -9,20 +9,20 @@
else if (Model.IsLayoutPageSelected) else if (Model.IsLayoutPageSelected)
{ {
@:@@{ @:@@{
@:ViewData["Title"] = @@SR["@Model.ViewName"]; @:ViewData["Title"] = @@Model.ViewName;
if (!string.IsNullOrEmpty(Model.LayoutPageFile)) if (!string.IsNullOrEmpty(Model.LayoutPageFile))
{ {
@:Layout = "@Model.LayoutPageFile"; @:Layout = "@Model.LayoutPageFile";
} }
@:} @:}
@: @:
@:<h2>@@SR["@Model.ViewName"]</h2> @:<h2>@@Model.ViewName</h2>
@: @:
} }
else else
{ {
@:@@{ @:@@{
@:Layout = null; @:Layout = "null";
@:} @:}
@: @:
@:<!DOCTYPE html> @:<!DOCTYPE html>
@ -38,9 +38,9 @@
} }
@:<form asp-action="@Model.ViewName"> @:<form asp-action="@Model.ViewName">
@:<div class="form-horizontal"> @:<div class="form-horizontal">
@:<h4>@@SR["@Model.ViewDataTypeShortName"]</h4> @:<h4>@@Model.ViewDataTypeShortName"]</h4>
@:<hr /> @:<hr />
@:<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div> @:<div asp-validation-summary="ModelOnly" class="text-danger"></div>
foreach (var property in Model.ModelMetadata.Properties) foreach (var property in Model.ModelMetadata.Properties)
{ {
if (property.Scaffold && !property.IsAutoGenerated && !property.IsReadOnly) if (property.Scaffold && !property.IsAutoGenerated && !property.IsReadOnly)
@ -107,7 +107,7 @@
</form> </form>
<div> <div>
<a asp-action="Index">@@SR["Back to List"]</a> <a asp-action="Index">@Back to List</a>
</div> </div>
@{ @{
@ -142,4 +142,4 @@
{ {
return string.Equals("System.Guid", property.TypeName, StringComparison.OrdinalIgnoreCase); return string.Equals("System.Guid", property.TypeName, StringComparison.OrdinalIgnoreCase);
} }
} }

@ -9,20 +9,20 @@
else if (Model.IsLayoutPageSelected) else if (Model.IsLayoutPageSelected)
{ {
@:@@{ @:@@{
@:ViewData["Title"] = @@SR["@Model.ViewName"]; @:ViewData["Title"] = @@Model.ViewName;
if (!string.IsNullOrEmpty(Model.LayoutPageFile)) if (!string.IsNullOrEmpty(Model.LayoutPageFile))
{ {
@:Layout = "@Model.LayoutPageFile"; @:Layout = "@Model.LayoutPageFile";
} }
@:} @:}
@: @:
@:<h2>@@SR["@Model.ViewName"]</h2> @:<h2>@@Model.ViewName</h2>
@: @:
} }
else else
{ {
@:@@{ @:@@{
@:Layout = null; @:Layout = "null";
@:} @:}
@: @:
@:<!DOCTYPE html> @:<!DOCTYPE html>
@ -30,16 +30,16 @@
@:<html> @:<html>
@:<head> @:<head>
@:<meta name="viewport" content="width=device-width" /> @:<meta name="viewport" content="width=device-width" />
@:<title>@@SR[@Model.ViewName]</title> @:<title>@@@Model.ViewName</title>
@:</head> @:</head>
@:<body> @:<body>
@: @:
// PushIndent(" "); // PushIndent(" ");
} }
} }
<h3>@@SR["AreYourSureYouWantToDeleteThis"]</h3> <h3>@AreYourSureYouWantToDeleteThis</h3>
<div> <div>
<h4>@@SR[@Model.ViewDataTypeShortName]</h4> <h4>@@@Model.ViewDataTypeShortName</h4>
<hr /> <hr />
<dl class="dl-horizontal"> <dl class="dl-horizontal">
@{ @{
@ -59,8 +59,8 @@
@: @:
@:<form asp-action="@Model.ViewName"> @:<form asp-action="@Model.ViewName">
@:<div class="form-actions no-color"> @:<div class="form-actions no-color">
@:<input type="submit" value="@@SR["Delete"]" class="btn btn-default" /> | @:<input type="submit" value="@Delete" class="btn btn-default" /> |
@:<a asp-action="Index">@@SR["Back to List"]</a> @:<a asp-action="Index">Back to List</a>
@:</div> @:</div>
@:</form> @:</form>
@:</div> @:</div>
@ -78,4 +78,4 @@
//Todo: Get the association for the property and use that. //Todo: Get the association for the property and use that.
return property.PropertyName; return property.PropertyName;
} }
} }

@ -9,20 +9,20 @@
else if (Model.IsLayoutPageSelected) else if (Model.IsLayoutPageSelected)
{ {
@:@@{ @:@@{
@:ViewData["Title"] = @@SR["@Model.ViewName"]; @:ViewData["Title"] = @@Model.ViewName;
if (!string.IsNullOrEmpty(Model.LayoutPageFile)) if (!string.IsNullOrEmpty(Model.LayoutPageFile))
{ {
@:Layout = "@Model.LayoutPageFile"; @:Layout = "@Model.LayoutPageFile";
} }
@:} @:}
@: @:
@:<h2>@@SR["@Model.ViewName"]</h2> @:<h2>@@Model.ViewName</h2>
@: @:
} }
else else
{ {
@:@@{ @:@@{
@:Layout = null; @:Layout = "null";
@:} @:}
@: @:
@:<!DOCTYPE html> @:<!DOCTYPE html>
@ -61,13 +61,13 @@
string pkName = GetPrimaryKeyName(); string pkName = GetPrimaryKeyName();
if (pkName != null) if (pkName != null)
{ {
@:<a asp-action="Edit" asp-route-id="@@Model.@pkName">@@SR["Edit"]</a> | @:<a asp-action="Edit" asp-route-id="@@Model.@pkName">@Edit</a> |
@:<a asp-action="Index">@@SR["Back to List"]</a> @:<a asp-action="Index">Back to List</a>
} }
else else
{ {
@:@@Html.ActionLink(@@SR["Edit"], "Edit", new { /* id = Model.PrimaryKey */ }) | @:@@Html.ActionLink(@Edit, "Edit", new { /* id = Model.PrimaryKey */ }) |
@:<a asp-action="Index">@@SR["Back to List"]</a> @:<a asp-action="Index">Back to List</a>
} }
}</p> }</p>
@{ @{
@ -92,4 +92,4 @@
//Todo: Get the association for the property and use that. //Todo: Get the association for the property and use that.
return property.PropertyName; return property.PropertyName;
} }
} }

@ -9,20 +9,20 @@
else if (Model.IsLayoutPageSelected) else if (Model.IsLayoutPageSelected)
{ {
@:@@{ @:@@{
@:ViewData["Title"] = @@SR["@Model.ViewName"]; @:ViewData["Title"] = @@Model.ViewName;
if (!string.IsNullOrEmpty(Model.LayoutPageFile)) if (!string.IsNullOrEmpty(Model.LayoutPageFile))
{ {
@:Layout = "@Model.LayoutPageFile"; @:Layout = "@Model.LayoutPageFile";
} }
@:} @:}
@: @:
@:<h2>@@SR["@Model.ViewName"]</h2> @:<h2>@@Model.ViewName</h2>
@: @:
} }
else else
{ {
@:@@{ @:@@{
@:Layout = null; @:Layout = "null";
@:} @:}
@: @:
@:<!DOCTYPE html> @:<!DOCTYPE html>
@ -30,7 +30,7 @@
@:<html> @:<html>
@:<head> @:<head>
@:<meta name="viewport" content="width=device-width" /> @:<meta name="viewport" content="width=device-width" />
@:<title>@@SR["@Model.ViewName"]</title> @:<title>@@Model.ViewName</title>
@:</head> @:</head>
@:<body> @:<body>
@: @:
@ -40,7 +40,7 @@
@:<div class="form-horizontal"> @:<div class="form-horizontal">
@:<h4>@Model.ViewDataTypeShortName</h4> @:<h4>@Model.ViewDataTypeShortName</h4>
@:<hr /> @:<hr />
@:<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div> @:<div asp-validation-summary="ModelOnly" class="text-danger"></div>
foreach (PropertyMetadata property in Model.ModelMetadata.Properties) foreach (PropertyMetadata property in Model.ModelMetadata.Properties)
{ {
if (property.Scaffold) if (property.Scaffold)
@ -111,7 +111,7 @@
</form> </form>
<div> <div>
<a asp-action="Index">@@SR["Back to List"]</a> <a asp-action="Index">Back to List</a>
</div> </div>
@{ @{

@ -9,20 +9,20 @@
else if (Model.IsLayoutPageSelected) else if (Model.IsLayoutPageSelected)
{ {
@:@@{ @:@@{
@:ViewData["Title"] = @@SR["@Model.ViewName"]; @:ViewData["Title"] = @@Model.ViewName;
if (!string.IsNullOrEmpty(Model.LayoutPageFile)) if (!string.IsNullOrEmpty(Model.LayoutPageFile))
{ {
@:Layout = "@Model.LayoutPageFile"; @:Layout = "@Model.LayoutPageFile";
} }
@:} @:}
@: @:
@:<h2>@@SR["@Model.ViewName"]</h2> @:<h2>@@Model.ViewName</h2>
@: @:
} }
else else
{ {
@:@@{ @:@@{
@:Layout = null; @:Layout = "null";
@:} @:}
@: @:
@:<!DOCTYPE html> @:<!DOCTYPE html>
@ -30,13 +30,13 @@
@:<html> @:<html>
@:<head> @:<head>
@:<meta name="viewport" content="width=device-width" /> @:<meta name="viewport" content="width=device-width" />
@:<title>@@SR["@Model.ViewName"]</title> @:<title>@@Model.ViewName</title>
@:</head> @:</head>
@:<body> @:<body>
// PushIndent(" "); // PushIndent(" ");
} }
@:<p> @:<p>
@:<a asp-action="Create">@@SR["Create New"]</a> @:<a asp-action="Create">Create New</a>
@:</p> @:</p>
@:<table class="table"> @:<table class="table">
@:<tr> @:<tr>
@ -69,17 +69,17 @@
if (pkName != null) if (pkName != null)
{ {
@:<td> @:<td>
@:<a asp-action="Edit" asp-route-id="@@item.@pkName">@@SR["Edit"]</a> | @:<a asp-action="Edit" asp-route-id="@@item.@pkName">@Edit</a> |
@:<a asp-action="Details" asp-route-id="@@item.@pkName">@@SR["Details"]</a> | @:<a asp-action="Details" asp-route-id="@@item.@pkName">@Details</a> |
@:<a asp-action="Delete" asp-route-id="@@item.@pkName">@@SR["Delete"]</a> @:<a asp-action="Delete" asp-route-id="@@item.@pkName">@Delete</a>
@:</td> @:</td>
} }
else else
{ {
<td> <td>
@@Html.ActionLink(SR["Edit"], "Edit",new { /* id=item.PrimaryKey */ }) | @@Html.ActionLink("Edit", "Edit",new { /* id=item.PrimaryKey */ }) |
@@Html.ActionLink(SR["Details"], "Details", new { /* id=item.PrimaryKey */ }) | @@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@@Html.ActionLink(SR["Delete"], "Delete", new { /* id=item.PrimaryKey */ }) @@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td> </td>
} }
@:</tr> @:</tr>
@ -112,4 +112,4 @@
{ {
return "IEnumerable<" + typeName + ">"; return "IEnumerable<" + typeName + ">";
} }
} }

@ -19,10 +19,10 @@ namespace Yavsc
public const string CompanyClaimType = "https://schemas.pschneider.fr/identity/claims/Company"; public const string CompanyClaimType = "https://schemas.pschneider.fr/identity/claims/Company";
public const string UserNameRegExp = @"^[a-zA-Z][a-zA-Z0-9._-]*$"; public const string UserNameRegExp = @"^[a-zA-Z][a-zA-Z0-9._-]*$";
public const string UserFileNamePatternRegExp = @"^([a-zA-Z0-9._-]*/)*[a-zA-Z0-9._-]+$"; public const string UserFileNamePatternRegExp = @"^([a-zA-Z0-9._-]*/)*[a-zA-Z0-9._-]+$";
public const string AuthorizePath = "~/authorize"; public const string AuthorizePath = "/authorize";
public const string TokenPath = "~/token"; public const string TokenPath = "/token";
public const string LoginPath = "~/signin"; public const string LoginPath = "/signin";
public const string LogoutPath = "~/signout"; public const string LogoutPath = "/signout";
public const string SignalRPath = "/api/signalr"; public const string SignalRPath = "/api/signalr";

@ -26,6 +26,7 @@ namespace Yavsc.Models.Google.Calendar
/// <summary> /// <summary>
/// Calendar list. /// Calendar list.
/// </summary> /// </summary>
[Obsolete("use Google.Apis")]
public class CalendarList { public class CalendarList {
/// <summary> /// <summary>
/// Gets or sets the kind. /// Gets or sets the kind.

@ -27,6 +27,7 @@ namespace Yavsc.Models.Google.Calendar
/// Calendar list entry. /// Calendar list entry.
/// </summary> /// </summary>
/// ///
[Obsolete("use GoogleUse.Apis")]
public class CalendarListEntry { public class CalendarListEntry {
/// <summary> /// <summary>
/// Gets or sets the kind. /// Gets or sets the kind.

@ -10,7 +10,7 @@ public class CiBuildSettings
/// The global process environment variables /// The global process environment variables
/// </summary> /// </summary>
/// <value></value> /// <value></value>
[JsonPropertyAttribute("env")] [JsonProperty("env")]
public string[] Environment { get; set; } public string[] Environment { get; set; }
/// <summary> /// <summary>

@ -9,7 +9,7 @@ namespace Yavsc.Services
{ {
// TODO ensure a default value at using this: // TODO ensure a default value at using this:
/// <summary> /// <summary>
/// maps a command type name to a bolling code, used to get bill assets /// maps a command type name to a billing code, used to get bill assets
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
Dictionary<string,string> BillingMap { get; } Dictionary<string,string> BillingMap { get; }
@ -33,7 +33,7 @@ namespace Yavsc.Services
/// </summary> /// </summary>
/// <param name="activityCode"></param> /// <param name="activityCode"></param>
/// <returns></returns> /// <returns></returns>
Task<IQueryable<ISpecializationSettings>> GetPerformersSettingsAsync(string activityCode); Task<IEnumerable<ISpecializationSettings>> GetPerformersSettingsAsync(string activityCode);
/// <summary> /// <summary>
/// Perfomer settings for the specified performer in the activity /// Perfomer settings for the specified performer in the activity

@ -1,19 +0,0 @@
using System.Threading.Tasks;
using Yavsc.Abstract.Manage;
namespace Yavsc.Services
{
public interface IEmailSender
{
/// <summary>
/// Sends en email.
/// </summary>
/// <param name="username">user name in database</param>
/// <param name="email">user's email</param>
/// <param name="subject">email subject</param>
/// <param name="message">message</param>
/// <returns>the message id</returns>
Task<EmailSentViewModel> SendEmailAsync(string username, string email, string subject, string message);
}
}

@ -1,3 +1,4 @@
using System;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
@ -15,35 +16,42 @@ namespace Yavsc.Models.Messaging
/// The title. /// The title.
/// </summary> /// </summary>
[Required, Display(Name = "Titre")] [Required, Display(Name = "Titre")]
[StringLength(1024)]
public string title { get; set; } public string title { get; set; }
/// <summary> /// <summary>
/// The body. /// The body.
/// </summary> /// </summary>
[StringLength(512)]
[Required, Display(Name = "Corps")] [Required, Display(Name = "Corps")]
public string body { get; set; } public string body { get; set; }
/// <summary> /// <summary>
/// The icon. /// The icon.
/// </summary> /// </summary>
[StringLength(512)]
[Display(Name = "Icône")] [Display(Name = "Icône")]
public string icon { get; set; } public string icon { get; set; }
/// <summary> /// <summary>
/// The sound. /// The sound.
/// </summary> /// </summary>
[StringLength(512)]
[Display(Name = "Son")] [Display(Name = "Son")]
public string sound { get; set; } public string sound { get; set; }
/// <summary> /// <summary>
/// The tag. /// The tag.
/// </summary> /// </summary>
[StringLength(512)]
[Display(Name = "Tag")] [Display(Name = "Tag")]
public string tag { get; set; } public string tag { get; set; }
/// <summary> /// <summary>
/// The color. /// The color.
/// </summary> /// </summary>
[StringLength(512)]
[Display(Name = "Couleur")] [Display(Name = "Couleur")]
public string color { get; set; } public string color { get; set; }
/// <summary> /// <summary>
/// The click action. /// The click action.
/// </summary> /// </summary>
[StringLength(512)]
[Required, Display(Name = "Label du click")] [Required, Display(Name = "Label du click")]
public string click_action { get; set; } public string click_action { get; set; }
@ -54,6 +62,7 @@ namespace Yavsc.Models.Messaging
/// <c>administration</c> : for admins ... /// <c>administration</c> : for admins ...
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[StringLength(512)]
public string Target { get; set; } public string Target { get; set; }
public Notification() public Notification()

@ -2,9 +2,10 @@ using System;
namespace Yavsc.Abstract.Workflow namespace Yavsc.Abstract.Workflow
{ {
public interface IDecidableQuery: IQuery public interface IDecidableQuery: IBaseTrackedEntity, IQuery
{ {
bool Rejected { get; set; } bool Decided { get; set; }
DateTime RejectedAt { get; set; } bool Accepted { get; set; }
} }
} }

@ -1,15 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Folder Include="wwwroot\" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.3" /> <Reference Include="System.ComponentModel.DataAnnotations" />
</ItemGroup> </ItemGroup>
</Project> </Project>

@ -19,6 +19,6 @@
</metadata> </metadata>
<files> <files>
<file src="bin/$config$/dnx451/Yavsc.Abstract.dll" target="lib/dnx451" /> <file src="bin/$config$/dnx451/Yavsc.Abstract.dll" target="lib/dnx451" />
<file src="bin/$config$/net451/Yavsc.Abstract.dll" target="lib/portable-net45+win8+wp8+wpa81+Xamarin.Mac+MonoAndroid10+MonoTouch10+Xamarin.iOS10" /> <file src="bin/$config$/net451/Yavsc.Abstract.dll" target="lib/portable-net45+win8+wp8+wpa81+Xamarin.Mac+MonoAndroid10+MonoTouch10+Xamarin.iOS10+monoandroid90" />
</files> </files>
</package> </package>

@ -1,27 +0,0 @@
//
// ICalendarManager.cs
//
// Author:
// Paul Schneider <paul@pschneider.fr>
//
// Copyright (c) 2015 GNU GPL
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
namespace Yavsc.Services
{
public class Event
{
}
}

@ -1,27 +0,0 @@
//
// ICalendarManager.cs
//
// Author:
// Paul Schneider <paul@pschneider.fr>
//
// Copyright (c) 2015 GNU GPL
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
namespace Yavsc.Services
{
public class Events
{
}
}

@ -20,11 +20,11 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
using System; using System;
using Google.Apis.Calendar.v3.Data;
namespace Yavsc.Services namespace Yavsc.Services
{ {
using System.Threading.Tasks; using System.Threading.Tasks;
using Yavsc.Models.Google.Calendar;
using Yavsc.ViewModels.Calendar; using Yavsc.ViewModels.Calendar;
/// <summary> /// <summary>

@ -19,6 +19,7 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Yavsc.Server.Models.Calendar;
namespace Yavsc.Models.Calendar namespace Yavsc.Models.Calendar
{ {

@ -19,6 +19,8 @@
// You should have received a copy of the GNU Lesser General Public License // You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
using Yavsc.Server.Models.Calendar;
namespace Yavsc.Models.Calendar namespace Yavsc.Models.Calendar
{ {
public interface IScheduledEvent public interface IScheduledEvent
@ -31,4 +33,4 @@ namespace Yavsc.Models.Calendar
Period Period { get; set; } Period Period { get; set; }
} }
} }

@ -1,23 +1,19 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Identity;
using Yavsc.Models.Relationship;
using Yavsc.Models.Identity;
using Yavsc.Models.Chat;
using Yavsc.Models.Bank;
using Yavsc.Models.Access;
namespace Yavsc.Models namespace Yavsc.Models
{ {
using Models.Relationship; [Table("AspNetUsers")]
using Models.Identity; public class ApplicationUser : IdentityUser
using Models.Chat;
using Models.Bank;
using Models.Access;
using Newtonsoft.Json;
using System;
using Microsoft.AspNetCore.Identity;
public class ApplicationUser : IdentityUser, IBaseTrackedEntity
{ {
/// <summary> /// <summary>
/// Another me, as a byte array. /// Another me, as a byte array.TG7@Eu%80rufzkhbb
/// This value points a picture that may be used /// This value points a picture that may be used
/// to present the user /// to present the user
/// </summary> /// </summary>
@ -36,31 +32,31 @@ namespace Yavsc.Models
/// WIP Paypal /// WIP Paypal
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Display(Name="Account balance")] [Display(Name = "Account balance")]
public virtual AccountBalance AccountBalance { get; set; } public virtual AccountBalance AccountBalance { get; set; }
/// <summary> /// <summary>
/// User's posts /// User's posts
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[InverseProperty("Author"),JsonIgnore] [InverseProperty("Author"), JsonIgnore]
public virtual List<Blog.BlogPost> Posts { get; set; } public virtual List<Blog.BlogPost> Posts { get; set; }
/// <summary> /// <summary>
/// User's contact list /// User's contact list
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[InverseProperty("Owner"),JsonIgnore] [InverseProperty("Owner"), JsonIgnore]
public virtual List<Contact> Book { get; set; } public virtual List<Contact> Book { get; set; }
/// <summary> /// <summary>
/// External devices using the API /// External devices using the API
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[InverseProperty("DeviceOwner"),JsonIgnore] [InverseProperty("DeviceOwner"), JsonIgnore]
public virtual List<DeviceDeclaration> DeviceDeclaration { get; set; } public virtual List<DeviceDeclaration> DeviceDeclaration { get; set; }
[InverseProperty("Owner"),JsonIgnore] [InverseProperty("Owner"), JsonIgnore]
public virtual List<ChatConnection> Connections { get; set; } public virtual List<ChatConnection> Connections { get; set; }
@ -68,16 +64,16 @@ namespace Yavsc.Models
/// User's circles /// User's circles
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[InverseProperty("Owner"),JsonIgnore] [InverseProperty("Owner"), JsonIgnore]
public virtual List<Circle> Circles { get; set; } public virtual List<Circle> Circles { get; set; }
/// <summary> /// <summary>
/// Billing postal address /// Billing postal address
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[ForeignKeyAttribute("PostalAddressId")] [ForeignKey("PostalAddressId")]
public virtual Location PostalAddress { get; set; } public virtual Location? PostalAddress { get; set; }
public long? PostalAddressId { get; set; } public long? PostalAddressId { get; set; }
/// <summary> /// <summary>
@ -87,49 +83,35 @@ namespace Yavsc.Models
[MaxLength(512)] [MaxLength(512)]
public string DedicatedGoogleCalendar { get; set; } public string DedicatedGoogleCalendar { get; set; }
public override string ToString() { public override string ToString()
return this.Id+" "+this.AccountBalance?.Credits.ToString()+this.Email+" "+this.UserName+" $"+this.AccountBalance?.Credits.ToString(); {
return this.Id + " " + this.AccountBalance?.Credits.ToString() + this.Email + " " + this.UserName + " $" + this.AccountBalance?.Credits.ToString();
} }
public BankIdentity BankInfo { get; set; } public virtual List<BankIdentity> BankInfo { get; set; }
public long DiskQuota { get; set; } = 512*1024*1024; public long DiskQuota { get; set; } = 512 * 1024 * 1024;
public long DiskUsage { get; set; } = 0; public long DiskUsage { get; set; } = 0;
public long MaxFileSize { get; set; } = 512*1024*1024; public long MaxFileSize { get; set; } = 512 * 1024 * 1024;
[JsonIgnore][InverseProperty("Owner")] [JsonIgnore]
[InverseProperty("Owner")]
public virtual List<BlackListed> BlackList { get; set; } public virtual List<BlackListed> BlackList { get; set; }
public bool AllowMonthlyEmail { get; set; } = false; public bool AllowMonthlyEmail { get; set; } = false;
[JsonIgnore][InverseProperty("Owner")] [JsonIgnore]
[InverseProperty("Owner")]
public virtual List<ChatRoom> Rooms { get; set; } public virtual List<ChatRoom> Rooms { get; set; }
[JsonIgnore][InverseProperty("User")] [JsonIgnore]
[InverseProperty("User")]
public virtual List<ChatRoomAccess> RoomAccess { get; set; } public virtual List<ChatRoomAccess> RoomAccess { get; set; }
[JsonIgnore][InverseProperty("Member")] [JsonIgnore]
[InverseProperty("Member")]
public virtual List<CircleMember> Membership { get; set; } public virtual List<CircleMember> Membership { get; set; }
public DateTime DateCreated
{
get; set;
}
public string UserCreated
{
get; set;
}
public DateTime DateModified
{
get; set;
}
public string UserModified
{
get; set;
}
} }
} }

@ -58,7 +58,22 @@ namespace Yavsc.Models.Bank
[DisplayName("Clé RIB")] [DisplayName("Clé RIB")]
public int BankedKey { get; set; } public int BankedKey { get; set; }
public virtual ApplicationUser User { get; set; }
public string UserId { get; set; }
public override bool Equals(object? obj)
{
if (obj==null) return false;
if (! typeof(BankIdentity).IsAssignableFrom(obj.GetType())) return false;
BankIdentity tobj = (BankIdentity)obj;
return tobj.IBAN == IBAN &&
tobj.BIC == BIC &&
tobj.AccountNumber == AccountNumber &&
tobj.BankedKey == BankedKey;
}
} }
} }

@ -13,7 +13,7 @@ namespace Yavsc.Models.Billing
using Yavsc.Abstract.Workflow; using Yavsc.Abstract.Workflow;
using Yavsc.Services; using Yavsc.Services;
public abstract class NominativeServiceCommand : IBaseTrackedEntity, IDecidableQuery, IIdentified<long> public abstract class NominativeServiceCommand : IDecidableQuery, IIdentified<long>
{ {
public string GetInvoiceId() { return GetType().Name + "/" + Id; } public string GetInvoiceId() { return GetType().Name + "/" + Id; }
@ -78,9 +78,8 @@ namespace Yavsc.Models.Billing
[ForeignKey("ActivityCode"),JsonIgnore,Display(Name="Domaine d'activité")] [ForeignKey("ActivityCode"),JsonIgnore,Display(Name="Domaine d'activité")]
public virtual Activity Context  { get; set ; } public virtual Activity Context  { get; set ; }
public bool Rejected { get; set; } public bool Decided { get; set; }
public DateTime RejectedAt { get; set; }
public abstract System.Collections.Generic.List<IBillItem> GetBillItems(); public abstract System.Collections.Generic.List<IBillItem> GetBillItems();
@ -97,11 +96,12 @@ namespace Yavsc.Models.Billing
return $"facture-{bcode}-{Id}{ack}"; return $"facture-{bcode}-{Id}{ack}";
} }
[Display(Name = "PaymentId")] [ForeignKey("Regularisation")]
public string PaymentId { get; set; } public string PaymentId { get; set; }
[ForeignKey("PaymentId"), Display(Name = "Acquittement de la facture")] [Display(Name = "Acquittement de la facture")]
public virtual PayPalPayment Regularisation { get; set; } public virtual PayPalPayment Regularisation { get; set; }
public bool Accepted { get; set; }
} }
} }

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Linq; using System.Linq;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json; using Newtonsoft.Json;
using Yavsc.Abstract.Identity.Security; using Yavsc.Abstract.Identity.Security;
using Yavsc.Attributes.Validation; using Yavsc.Attributes.Validation;
@ -34,11 +35,11 @@ namespace Yavsc.Models.Blog
public string Title { get; set; } public string Title { get; set; }
[Display(Name="Identifiant de l'auteur")] [Display(Name="Identifiant de l'auteur")]
[ForeignKey("Author")]
public string AuthorId { get; set; } public string AuthorId { get; set; }
[Display(Name="Auteur")] [Display(Name="Auteur")]
[ForeignKey("AuthorId"),JsonIgnore] public virtual ApplicationUser Author { set; get; }
public ApplicationUser Author { set; get; }
[Display(Name="Visible")] [Display(Name="Visible")]
public bool Visible { get; set; } public bool Visible { get; set; }

@ -0,0 +1,9 @@
using Yavsc.Models.Calendar;
namespace Yavsc.Server.Models.Calendar
{
public class Availability : List<Period>
{
}
}

@ -22,7 +22,7 @@
using System; using System;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace Yavsc.Models.Calendar namespace Yavsc.Server.Models.Calendar
{ {
/// <summary> /// <summary>
/// Hollydays. /// Hollydays.

@ -19,7 +19,7 @@
// You should have received a copy of the GNU Lesser General Public License // You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
namespace Yavsc.Models.Calendar namespace Yavsc.Server.Models.Calendar
{ {
/// <summary> /// <summary>
/// Periodicity. /// Periodicity.

@ -21,9 +21,10 @@
namespace Yavsc.Models.Calendar using Yavsc.Models.Relationship;
namespace Yavsc.Server.Models.Calendar
{ {
using Models.Relationship;
/// <summary> /// <summary>
/// Position and keyphrase. /// Position and keyphrase.
/// </summary> /// </summary>

@ -21,6 +21,7 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using Yavsc.Server.Models.Calendar;
namespace Yavsc.Models.Calendar namespace Yavsc.Models.Calendar
{ {
@ -42,4 +43,4 @@ namespace Yavsc.Models.Calendar
set; set;
} }
} }
} }

@ -4,6 +4,7 @@ using System.ComponentModel.DataAnnotations.Schema;
using Yavsc.Attributes.Validation; using Yavsc.Attributes.Validation;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Calendar; using Yavsc.Models.Calendar;
using Yavsc.Server.Models.Calendar;
namespace Yavsc.Server.Models.EMailing namespace Yavsc.Server.Models.EMailing
{ {

@ -27,10 +27,10 @@ namespace Yavsc.Models.Workflow
[YaStringLength(512)] [YaStringLength(512)]
[Display(Name = "Code du parent")] [Display(Name = "Code du parent")]
[ForeignKey("Parent")]
public string ParentCode { get; set; } public string ParentCode { get; set; }
[ForeignKey("ParentCode"), JsonIgnore] [Display(Name = "Activité parent"), JsonIgnore]
[Display(Name = "Activité parent")]
public virtual Activity Parent { get; set; } public virtual Activity Parent { get; set; }
[InverseProperty("Parent"), JsonIgnore] [InverseProperty("Parent"), JsonIgnore]

@ -0,0 +1,12 @@
{
"profiles": {
"SelfHost": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:5001"
}
}
}

@ -1,7 +0,0 @@
namespace Yavsc.Server.Services
{
public class TranslationService
{
}
}

@ -7,21 +7,21 @@ namespace Yavsc
public string Title { get; set; } public string Title { get; set; }
public string Slogan { get; set; } public string Slogan { get; set; }
public string StyleSheet { get; set; } public string StyleSheet { get; set; }
public string FavIcon { get; set; } public string FavIcon { get; set; }
public string Logo { get; set; } public string Logo { get; set; }
/// <summary> /// <summary>
/// Conceptually, /// Conceptually,
/// This authorisation server only has this present site as unique audience. /// This authorisation server only has this present site as unique audience.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public string Audience { get; set; } public string Audience { get; set; }
/// <summary> /// <summary>
/// it's a very small company, with one domaine name only, /// it's a very small company, with one domaine name only,
/// so let it be the same as in the Audience field. /// so let it be the same as in the Audience field.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public string Authority { get; set; } public string Authority { get; set; }
/// <summary> /// <summary>
/// Owner's email /// Owner's email
/// </summary> /// </summary>
@ -34,16 +34,16 @@ namespace Yavsc
public Contact Admin { get; set; } public Contact Admin { get; set; }
public string DataDir { get; set; } public string DataDir { get; set; }
public string Avatars { get; set; } public string Avatars { get; set; } = "avatars";
public long Quota { get; set; } public long Quota { get; set; }
public string Blog { get; set; } public string Blog { get; set; } = "blogs";
public string Bills { get; set; } public string Bills { get; set; } = "bills";
public string GitRepository { get; set; } = "sources"; public string GitRepository { get; set; } = "sources";
public string BusinessName { get; set; } public string BusinessName { get; set; }
public string Street { get; set; } public string Street { get; set; }
public string PostalCode { get; set; } public string PostalCode { get; set; }
public string CountryCode { get; set; } public string CountryCode { get; set; }
public string HomeViewName { get; set; } public string HomeViewName { get; set; }
/// <summary> /// <summary>
@ -51,7 +51,7 @@ namespace Yavsc
/// generated pdf files using pandoc /// generated pdf files using pandoc
/// </summary> /// </summary>
/// <returns>The temporary directory to use</returns> /// <returns>The temporary directory to use</returns>
public string TempDir { get; set; } = "Temp"; public string TempDir { get; set; } = "temp";
/// <summary> /// <summary>
/// Only one performer will capture payments /// Only one performer will capture payments

@ -1,7 +0,0 @@
namespace Yavsc
{
public class ThirdPartyFiles {
}
}

@ -10,8 +10,7 @@ namespace Yavsc.Server.Settings
new Dictionary<string, Func<ApplicationUser, bool>> new Dictionary<string, Func<ApplicationUser, bool>>
{ {
{ "allow-monthly", u => u.AllowMonthlyEmail }, { "allow-monthly", u => u.AllowMonthlyEmail },
{ "email-not-confirmed", u => !u.EmailConfirmed && u.DateCreated < DateTime.Now.AddDays(-7) }, { "email-not-confirmed", u => !u.EmailConfirmed }
{ "user-to-remove", u => !u.EmailConfirmed && u.DateCreated < DateTime.Now.AddDays(-14) }
}; };
} }
} }

@ -8,6 +8,6 @@ namespace Yavsc.ViewModels.Account
{ {
[YaRequired] [YaRequired]
[YaStringLength(512)] [YaStringLength(512)]
public string LoginOrEmail { get; set; } public string? LoginOrEmail { get; set; }
} }
} }

@ -5,14 +5,16 @@ using Yavsc.Attributes.Validation;
namespace Yavsc.ViewModels.Account namespace Yavsc.ViewModels.Account
{ {
public class SignInViewModel // TODO external autentication providers
public class SignInModel
{ {
/// <summary> /// <summary>
/// Local user's name. /// Local user's name.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[YaRequired] [YaRequired]
public string UserName { get; set; } public string EMail { get; set; }
/// <summary> /// <summary>
/// Local user's password . /// Local user's password .
@ -45,11 +47,6 @@ namespace Yavsc.ViewModels.Account
/// <returns></returns> /// <returns></returns>
public string ReturnUrl { get; set; } public string ReturnUrl { get; set; }
/// <summary>
/// Lists external identity provider descriptions.
/// </summary>
/// <returns>an enumeration of the descriptions.</returns>
public IEnumerable<YaAuthenticationDescription> ExternalProviders { get; set; }
} }
public class YaAuthenticationDescription { public class YaAuthenticationDescription {

@ -18,7 +18,5 @@ namespace Yavsc.ViewModels.Account
[Display(Name = "Confirmer le mot de passe")] [Display(Name = "Confirmer le mot de passe")]
[Compare("Password", ErrorMessage = "Le mot de passe et sa confirmation ne sont pas les mêmes.")] [Compare("Password", ErrorMessage = "Le mot de passe et sa confirmation ne sont pas les mêmes.")]
public string ConfirmPassword { get; set; } public string ConfirmPassword { get; set; }
public string Code { get; set; }
} }
} }

@ -1,6 +1,6 @@
using System; using System;
using Yavsc.Models.Calendar; using Yavsc.Models.Calendar;
using Yavsc.Server.Models.Calendar;
namespace Yavsc.ViewModels.Calendar namespace Yavsc.ViewModels.Calendar
{ {

@ -1,5 +1,5 @@
using Yavsc.Models.Google.Calendar; using Google.Apis.Calendar.v3.Data;
namespace Yavsc.ViewModels.Calendar namespace Yavsc.ViewModels.Calendar
{ {

@ -1,17 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Folder Include="wwwroot\" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.2" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="8.0.1" />
<PackageReference Include="Google.Apis.Calendar.v3" Version="1.60.0.2993" />
<PackageReference Include="PayPalMerchantSDK" Version="2.16.250" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="../Yavsc.Abstract/Yavsc.Abstract.csproj" /> <Reference Include="System.ComponentModel.DataAnnotations" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.3" /> <Reference Include="System.Xml" />
<PackageReference Include="PayPalMerchantSDK" Version="2.16.250" /> <Reference Include="System.Net" />
<Reference Include="System.Net.Http" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../Yavsc.Abstract/Yavsc.Abstract.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

@ -0,0 +1,129 @@
{
"version": "1.0.5-*",
"description": "Yavsc server common library",
"authors": [
"Paul Schneider <paul@pschneider.fr>"
],
"packOptions": {
"repository": {
"type": "git",
"url": "https://github.com/pazof/yavsc"
},
"licenseUrl": "https://github.com/pazof/yavsc/blob/vnext/LICENSE",
"requireLicenseAcceptance": true,
"owners": [
"Paul Schneider <paul@pschneider.fr>"
],
"summary": "Yet another very small company",
"projectUrl": "http://yavsc.pschneider.fr",
"tags": [
"Blog",
"PoS",
"Chat"
]
},
"userSecretsId": "aspnet5-YavscWeb-a0dadd21-2ced-43d3-96f9-7e504345102f",
"buildOptions": {
"debugType": "full",
"emitEntryPoint": false,
"outputName": "Yavsc.Server",
"compile": {
"include": "*.cs",
"exclude": [
"wwwroot",
"node_modules",
"bower_components",
"contrib"
]
},
"embed": [
"Resources/**/*.resx"
],
"publicSign": false,
"keyFile": "../../../sgKey.snk",
"nowarn": ["IDE1006"]
},
"tooling": {
"defaultNamespace": "Yavsc"
},
"dependencies": {
"EntityFramework.Commands": "7.0.0-rc1-final",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-*",
"Microsoft.Extensions.Configuration.Abstractions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
"Microsoft.Extensions.Globalization.CultureInfoCache": "1.0.0-rc1-final",
"Microsoft.Extensions.Localization.Abstractions": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.TraceSource": "1.0.0-rc1-final",
"Microsoft.Extensions.Options": "0.0.1-alpha",
"Microsoft.Extensions.Localization": "1.0.0-rc1-final",
"Newtonsoft.Json": "7.0.1",
"Gapi.net45": "1.0.1",
"PayPalMerchant-net451": "2.7.109",
"MailKit": "1.12.0",
"Microsoft.CodeAnalysis.CSharp": "1.1.0-rc1-20151109-01",
"Yavsc.Abstract": {
"type": "build"
}
},
"frameworks": {
"dnx451": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0",
"System.Linq": "4.0.0",
"System.Net": "4.0.0.0",
"System.Net.Http": "4.0.0",
"System.Xml": "4.0.0"
}
},
"net451": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0",
"System.Net": "4.0.0.0",
"System.Net.Http": "4.0.0",
"System.Xml": "4.0.0",
"System": "4.0.0"
}
},
"net452": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0",
"System.Net": "4.0.0.0",
"System.Net.Http": "4.0.0",
"System.Xml": "4.0.0",
"System": "4.0.0"
}
},
"net46": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0",
"System.Net": "4.0.0.0",
"System.Net.Http": "4.0.0",
"System.Xml": "4.0.0",
"System": "4.0.0"
}
},
"net461": {
"frameworkAssemblies": {
"System.ComponentModel.DataAnnotations": "4.0.0",
"System.Net": "4.0.0.0",
"System.Net.Http": "4.0.0",
"System.Xml": "4.0.0",
"System": "4.0.0"
}
}
},
"commands": {
"ef": "EntityFramework.Commands",
"gen": "Microsoft.Extensions.CodeGeneration"
},
"scripts": {
"postrestore": [
"grep -v '\\.\\.dll' project.lock.json > new.project.lock.json",
"mv new.project.lock.json project.lock.json"
]
}
}

@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Blog; using Yavsc.Models.Blog;
@ -36,14 +37,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
BlogPost blog = _context.Blogspot.Single(m => m.Id == id); BlogPost blog = _context.Blogspot.Single(m => m.Id == id);
if (blog == null) if (blog == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(blog); return Ok(blog);
@ -55,25 +56,25 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != blog.Id) if (id != blog.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(blog).State = EntityState.Modified; _context.Entry(blog).State = EntityState.Modified;
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!BlogExists(id)) if (!BlogExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -81,7 +82,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/BlogApi // POST: api/BlogApi
@ -90,19 +91,19 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Blogspot.Add(blog); _context.Blogspot.Add(blog);
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (BlogExists(blog.Id)) if (BlogExists(blog.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -119,17 +120,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
BlogPost blog = _context.Blogspot.Single(m => m.Id == id); BlogPost blog = _context.Blogspot.Single(m => m.Id == id);
if (blog == null) if (blog == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.Blogspot.Remove(blog); _context.Blogspot.Remove(blog);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(blog); return Ok(blog);
} }

@ -32,14 +32,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
BlogTag blogTag = await _context.TagsDomain.SingleAsync(m => m.PostId == id); BlogTag blogTag = await _context.TagsDomain.SingleAsync(m => m.PostId == id);
if (blogTag == null) if (blogTag == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(blogTag); return Ok(blogTag);
@ -51,12 +51,12 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != blogTag.PostId) if (id != blogTag.PostId)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(blogTag).State = EntityState.Modified; _context.Entry(blogTag).State = EntityState.Modified;
@ -69,7 +69,7 @@ namespace Yavsc.Controllers
{ {
if (!BlogTagExists(id)) if (!BlogTagExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -77,7 +77,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/BlogTagsApi // POST: api/BlogTagsApi
@ -86,7 +86,7 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.TagsDomain.Add(blogTag); _context.TagsDomain.Add(blogTag);
@ -98,7 +98,7 @@ namespace Yavsc.Controllers
{ {
if (BlogTagExists(blogTag.PostId)) if (BlogTagExists(blogTag.PostId))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -115,13 +115,13 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
BlogTag blogTag = await _context.TagsDomain.SingleAsync(m => m.PostId == id); BlogTag blogTag = await _context.TagsDomain.SingleAsync(m => m.PostId == id);
if (blogTag == null) if (blogTag == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.TagsDomain.Remove(blogTag); _context.TagsDomain.Remove(blogTag);

@ -1,10 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Blog; using Yavsc.Models.Blog;
@ -34,14 +31,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id); Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
if (comment == null) if (comment == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(comment); return Ok(comment);
@ -53,25 +50,25 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != comment.Id) if (id != comment.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(comment).State = EntityState.Modified; _context.Entry(comment).State = EntityState.Modified;
try try
{ {
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!CommentExists(id)) if (!CommentExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -79,7 +76,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/CommentsApi // POST: api/CommentsApi
@ -92,7 +89,7 @@ namespace Yavsc.Controllers
} }
if (!User.IsInRole(Constants.AdminGroupName)) if (!User.IsInRole(Constants.AdminGroupName))
{ {
if (_userManager.GetUserId(User)!=comment.AuthorId) { if (User.GetUserId()!=comment.AuthorId) {
ModelState.AddModelError("Content","Vous ne pouvez pas poster au nom d'un autre."); ModelState.AddModelError("Content","Vous ne pouvez pas poster au nom d'un autre.");
return new BadRequestObjectResult(ModelState); return new BadRequestObjectResult(ModelState);
} }
@ -100,13 +97,13 @@ namespace Yavsc.Controllers
_context.Comment.Add(comment); _context.Comment.Add(comment);
try try
{ {
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (CommentExists(comment.Id)) if (CommentExists(comment.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -122,17 +119,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Comment comment = await _context.Comment.SingleAsync(m => m.Id == id); Comment comment = await _context.Comment.SingleAsync(m => m.Id == id);
if (comment == null) if (comment == null)
{ {
return StatusCode(404); return NotFound();
} }
RemoveRecursive(comment); RemoveRecursive(comment);
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
return Ok(comment); return Ok(comment);
} }

@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@ -63,11 +61,11 @@ namespace Yavsc.ApiControllers
} }
if (pathex!=null) { if (pathex!=null) {
_logger.LogError($"invalid sub path: '{subdir}'."); _logger.LogError($"invalid sub path: '{subdir}'.");
return HttpBadRequest(pathex); return BadRequest(pathex);
} }
_logger.LogInformation($"Receiving files, saved in '{destDir}' (specified as '{subdir}')."); _logger.LogInformation($"Receiving files, saved in '{destDir}' (specified as '{subdir}').");
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = dbContext.Users.Single( var user = dbContext.Users.Single(
u => u.Id == uid u => u.Id == uid
); );
@ -77,7 +75,7 @@ namespace Yavsc.ApiControllers
foreach (var f in Request.Form.Files) foreach (var f in Request.Form.Files)
{ {
var item = user.ReceiveUserFile(destDir, f); var item = user.ReceiveUserFile(destDir, f);
dbContext.SaveChanges(_userManager.GetUserId(User)); dbContext.SaveChanges(User.GetUserId());
received.Add(item); received.Add(item);
_logger.LogInformation($"Received '{item.FileName}'."); _logger.LogInformation($"Received '{item.FileName}'.");
if (item.QuotaOffensed) if (item.QuotaOffensed)
@ -91,7 +89,7 @@ namespace Yavsc.ApiControllers
[Authorize("AdministratorOnly")] [Authorize("AdministratorOnly")]
public IActionResult AddQuota(string uname, int len) public IActionResult AddQuota(string uname, int len)
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = dbContext.Users.FirstOrDefault( var user = dbContext.Users.FirstOrDefault(
u => u.UserName == uname u => u.UserName == uname
); );
@ -107,7 +105,7 @@ namespace Yavsc.ApiControllers
public IActionResult MoveFile([FromBody] RenameFileQuery query) public IActionResult MoveFile([FromBody] RenameFileQuery query)
{ {
if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState); if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState);
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = dbContext.Users.Single( var user = dbContext.Users.Single(
u => u.Id == uid u => u.Id == uid
); );
@ -124,15 +122,15 @@ namespace Yavsc.ApiControllers
if (!ModelState.IsValid) { if (!ModelState.IsValid) {
var idvr = new ValidRemoteUserFilePathAttribute(); var idvr = new ValidRemoteUserFilePathAttribute();
return this.HttpBadRequest(new { id = idvr.IsValid(query.id), to = idvr.IsValid(query.to), errors = ModelState }); return this.BadRequest(new { id = idvr.IsValid(query.id), to = idvr.IsValid(query.to), errors = ModelState });
} }
_logger.LogInformation($"Valid move query: {query.id} => {query.to}"); _logger.LogInformation($"Valid move query: {query.id} => {query.to}");
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = dbContext.Users.Single( var user = dbContext.Users.Single(
u => u.Id == uid u => u.Id == uid
); );
try { try {
if (Startup.UserFilesOptions.FileProvider.GetFileInfo(Path.Combine(user.UserName, query.id)).Exists) if (Config.UserFilesOptions.FileProvider.GetFileInfo(Path.Combine(user.UserName, query.id)).Exists)
{ {
var result = user.MoveUserFile(query.id, query.to); var result = user.MoveUserFile(query.id, query.to);
if (!result.Done) return new BadRequestObjectResult(result); if (!result.Done) return new BadRequestObjectResult(result);
@ -160,7 +158,7 @@ namespace Yavsc.ApiControllers
if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState); if (!ModelState.IsValid) return new BadRequestObjectResult(ModelState);
var user = dbContext.Users.Single( var user = dbContext.Users.Single(
u => u.Id == _userManager.GetUserId(User) u => u.Id == User.GetUserId()
); );
try { try {

@ -1,16 +1,13 @@
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Yavsc.Attributes.Validation; using Yavsc.Attributes.Validation;
using Yavsc.Helpers; using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Messaging; using Yavsc.Models.Messaging;
using Yavsc.Services; using Yavsc.Services;
using Microsoft.AspNetCore.SignalR;
namespace Yavsc.ApiControllers namespace Yavsc.ApiControllers
{ {
@ -19,13 +16,16 @@ namespace Yavsc.ApiControllers
{ {
private readonly ILogger logger; private readonly ILogger logger;
private readonly ILiveProcessor liveProcessor; private readonly ILiveProcessor liveProcessor;
private readonly IHubContext<ChatHub> hubContext;
readonly ApplicationDbContext dbContext; readonly ApplicationDbContext dbContext;
public FileSystemStreamController(ApplicationDbContext context, ILiveProcessor liveProcessor, ILoggerFactory loggerFactory) public FileSystemStreamController(ApplicationDbContext context, ILiveProcessor liveProcessor, ILoggerFactory loggerFactory,
IHubContext<ChatHub> hubContext)
{ {
this.dbContext = context; this.dbContext = context;
this.logger = loggerFactory.CreateLogger<FileSystemStreamController>(); this.logger = loggerFactory.CreateLogger<FileSystemStreamController>();
this.liveProcessor = liveProcessor; this.liveProcessor = liveProcessor;
this.hubContext = hubContext;
} }
[Authorize, Route("put/{filename}")] [Authorize, Route("put/{filename}")]
@ -33,28 +33,28 @@ namespace Yavsc.ApiControllers
{ {
logger.LogInformation("Put : " + filename); logger.LogInformation("Put : " + filename);
if (!HttpContext.WebSockets.IsWebSocketRequest) if (!HttpContext.WebSockets.IsWebSocketRequest)
return HttpBadRequest("not a web socket"); return BadRequest("not a web socket");
if (!HttpContext.User.Identity.IsAuthenticated) if (!HttpContext.User.Identity.IsAuthenticated)
return new HttpUnauthorizedResult(); return new UnauthorizedResult();
var subdirs = filename.Split('/'); var subdirs = filename.Split('/');
var filePath = subdirs.Length > 1 ? string.Join("/", subdirs.Take(subdirs.Length-1)) : null; var filePath = subdirs.Length > 1 ? string.Join("/", subdirs.Take(subdirs.Length-1)) : null;
var shortFileName = subdirs[subdirs.Length-1]; var shortFileName = subdirs[subdirs.Length-1];
if (!shortFileName.IsValidShortFileName()) if (!shortFileName.IsValidShortFileName())
{ {
logger.LogInformation("invalid file name : " + filename); logger.LogInformation("invalid file name : " + filename);
return HttpBadRequest("invalid file name"); return BadRequest("invalid file name");
} }
logger.LogInformation("validated: api/stream/Put: "+filename); logger.LogInformation("validated: api/stream/Put: "+filename);
var userName = User.GetUserName(); var userName = User.GetUserName();
var hubContext = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
string url = string.Format( string url = string.Format(
"{0}/{1}/{2}", "{0}/{1}/{2}",
Startup.UserFilesOptions.RequestPath.ToUriComponent(), Config.UserFilesOptions.RequestPath.ToUriComponent(),
userName, userName,
filename filename
); );
hubContext.Clients.All.addPublicStream(new PublicStreamInfo hubContext.Clients.All.SendAsync("addPublicStream", new PublicStreamInfo
{ {
sender = userName, sender = userName,
url = url, url = url,
@ -62,7 +62,7 @@ namespace Yavsc.ApiControllers
string destDir = HttpContext.User.InitPostToFileSystem(filePath); string destDir = HttpContext.User.InitPostToFileSystem(filePath);
logger.LogInformation($"Saving flow to {destDir}"); logger.LogInformation($"Saving flow to {destDir}");
var userId = _userManager.GetUserId(User); var userId = User.GetUserId();
var user = await dbContext.Users.FirstAsync(u => u.Id == userId); var user = await dbContext.Users.FirstAsync(u => u.Id == userId);
logger.LogInformation("Accepting stream ..."); logger.LogInformation("Accepting stream ...");
await liveProcessor.AcceptStream(HttpContext, user, destDir, shortFileName); await liveProcessor.AcceptStream(HttpContext, user, destDir, shortFileName);

@ -2,12 +2,13 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
using System.Security.Claims; using System.Security.Claims;
using Models; using Microsoft.EntityFrameworkCore;
using Models;
using Yavsc.Helpers;
using Yavsc.Models.Blog; using Yavsc.Models.Blog;
[Produces("application/json")] [Produces("application/json")]
@ -34,14 +35,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
BlogTag postTag = _context.TagsDomain.Single(m => m.PostId == id); BlogTag postTag = _context.TagsDomain.Single(m => m.PostId == id);
if (postTag == null) if (postTag == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(postTag); return Ok(postTag);
@ -53,25 +54,25 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != postTag.PostId) if (id != postTag.PostId)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(postTag).State = EntityState.Modified; _context.Entry(postTag).State = EntityState.Modified;
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!PostTagExists(id)) if (!PostTagExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -79,7 +80,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/PostTagsApi // POST: api/PostTagsApi
@ -88,19 +89,19 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.TagsDomain.Add(postTag); _context.TagsDomain.Add(postTag);
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (PostTagExists(postTag.PostId)) if (PostTagExists(postTag.PostId))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -117,17 +118,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
BlogTag postTag = _context.TagsDomain.Single(m => m.PostId == id); BlogTag postTag = _context.TagsDomain.Single(m => m.PostId == id);
if (postTag == null) if (postTag == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.TagsDomain.Remove(postTag); _context.TagsDomain.Remove(postTag);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(postTag); return Ok(postTag);
} }

@ -1,15 +1,14 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models; using Yavsc.Models;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
using System.Security.Claims; using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
using Models.Relationship; using Models.Relationship;
using Yavsc.Helpers;
[Produces("application/json")] [Produces("application/json")]
[Route("api/TagsApi")] [Route("api/TagsApi")]
public class TagsApiController : Controller public class TagsApiController : Controller
@ -37,14 +36,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Tag tag = _context.Tags.Single(m => m.Id == id); Tag tag = _context.Tags.Single(m => m.Id == id);
if (tag == null) if (tag == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(tag); return Ok(tag);
@ -56,26 +55,26 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != tag.Id) if (id != tag.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(tag).State = EntityState.Modified; _context.Entry(tag).State = EntityState.Modified;
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
_logger.LogInformation("Tag created"); _logger.LogInformation("Tag created");
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!TagExists(id)) if (!TagExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -83,7 +82,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/TagsApi // POST: api/TagsApi
@ -92,19 +91,19 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Tags.Add(tag); _context.Tags.Add(tag);
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (TagExists(tag.Id)) if (TagExists(tag.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -121,17 +120,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Tag tag = _context.Tags.Single(m => m.Id == id); Tag tag = _context.Tags.Single(m => m.Id == id);
if (tag == null) if (tag == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.Tags.Remove(tag); _context.Tags.Remove(tag);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(tag); return Ok(tag);
} }

@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Workflow; using Yavsc.Models.Workflow;
@ -37,14 +38,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Activity activity = await _context.Activities.SingleAsync(m => m.Code == id); Activity activity = await _context.Activities.SingleAsync(m => m.Code == id);
if (activity == null) if (activity == null)
{ {
return StatusCode(404); return NotFound();
} }
// Also return hidden ones // Also return hidden ones
// hidden doesn't mean disabled // hidden doesn't mean disabled
@ -57,25 +58,25 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != activity.Code) if (id != activity.Code)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(activity).State = EntityState.Modified; _context.Entry(activity).State = EntityState.Modified;
try try
{ {
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!ActivityExists(id)) if (!ActivityExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -83,7 +84,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/ActivityApi // POST: api/ActivityApi
@ -92,19 +93,19 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Activities.Add(activity); _context.Activities.Add(activity);
try try
{ {
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (ActivityExists(activity.Code)) if (ActivityExists(activity.Code))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -121,17 +122,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Activity activity = await _context.Activities.SingleAsync(m => m.Code == id); Activity activity = await _context.Activities.SingleAsync(m => m.Code == id);
if (activity == null) if (activity == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.Activities.Remove(activity); _context.Activities.Remove(activity);
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
return Ok(activity); return Ok(activity);
} }

@ -1,15 +1,7 @@
using System.IO;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Web.Routing;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using Newtonsoft.Json; using Newtonsoft.Json;
using System;
using System.Security.Claims; using System.Security.Claims;
using Yavsc.Helpers; using Yavsc.Helpers;
using Yavsc.ViewModels; using Yavsc.ViewModels;
@ -21,6 +13,8 @@ namespace Yavsc.ApiControllers
using Models.Messaging; using Models.Messaging;
using ViewModels.Auth; using ViewModels.Auth;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
[Route("api/bill"), Authorize] [Route("api/bill"), Authorize]
public class BillingController : Controller public class BillingController : Controller
@ -38,7 +32,7 @@ namespace Yavsc.ApiControllers
public BillingController( public BillingController(
IAuthorizationService authorizationService, IAuthorizationService authorizationService,
ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
IStringLocalizer<Yavsc.YavscLocalisation> SR, IStringLocalizer<Yavsc.YavscLocalization> SR,
ApplicationDbContext context, ApplicationDbContext context,
IOptions<GoogleAuthSettings> googleSettings, IOptions<GoogleAuthSettings> googleSettings,
IYavscMessageSender GCMSender, IYavscMessageSender GCMSender,
@ -59,7 +53,7 @@ namespace Yavsc.ApiControllers
{ {
var bill = await billingService.GetBillAsync(billingCode, id); var bill = await billingService.GetBillAsync(billingCode, id);
if (!await authorizationService.AuthorizeAsync(User, bill, new ViewRequirement())) if ( authorizationService.AuthorizeAsync(User, bill, new ViewRequirement()).IsFaulted)
{ {
return new ChallengeResult(); return new ChallengeResult();
} }
@ -77,11 +71,11 @@ namespace Yavsc.ApiControllers
if (bill==null) { if (bill==null) {
logger.LogCritical ( $"# not found !! {id} in {billingCode}"); logger.LogCritical ( $"# not found !! {id} in {billingCode}");
return this.StatusCode(404); return this.NotFound();
} }
logger.LogVerbose(JsonConvert.SerializeObject(bill)); logger.LogTrace(JsonConvert.SerializeObject(bill));
if (!await authorizationService.AuthorizeAsync(User, bill, new ViewRequirement())) if (!(await authorizationService.AuthorizeAsync(User, bill, new ViewRequirement())).Succeeded)
{ {
return new ChallengeResult(); return new ChallengeResult();
} }
@ -96,7 +90,7 @@ namespace Yavsc.ApiControllers
if (bill==null) { if (bill==null) {
logger.LogCritical ( $"# not found !! {id} in {billingCode}"); logger.LogCritical ( $"# not found !! {id} in {billingCode}");
return this.StatusCode(404); return this.NotFound();
} }
logger.LogWarning("Got bill ack:"+bill.GetIsAcquitted().ToString()); logger.LogWarning("Got bill ack:"+bill.GetIsAcquitted().ToString());
return ViewComponent("Bill",new object[] { billingCode, bill, OutputFormat.Pdf, true } ); return ViewComponent("Bill",new object[] { billingCode, bill, OutputFormat.Pdf, true } );
@ -112,7 +106,9 @@ namespace Yavsc.ApiControllers
.FirstOrDefault(e=>e.Id == id); .FirstOrDefault(e=>e.Id == id);
if (estimate == null) if (estimate == null)
return new BadRequestResult(); return new BadRequestResult();
if (!await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement())) if (!(await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement())).Succeeded)
{ {
return new ChallengeResult(); return new ChallengeResult();
} }
@ -120,7 +116,7 @@ namespace Yavsc.ApiControllers
return new BadRequestResult(); return new BadRequestResult();
User.ReceiveProSignature(billingCode,id,Request.Form.Files[0],"pro"); User.ReceiveProSignature(billingCode,id,Request.Form.Files[0],"pro");
estimate.ProviderValidationDate = DateTime.Now; estimate.ProviderValidationDate = DateTime.Now;
dbContext.SaveChanges(_userManager.GetUserId(User)); dbContext.SaveChanges(User.GetUserId());
// Notify the client // Notify the client
var locstr = _localizer["EstimationMessageToClient"]; var locstr = _localizer["EstimationMessageToClient"];
@ -138,25 +134,26 @@ namespace Yavsc.ApiControllers
{ {
// For authorization purpose // For authorization purpose
var estimate = dbContext.Estimates.FirstOrDefault(e=>e.Id == id); var estimate = dbContext.Estimates.FirstOrDefault(e=>e.Id == id);
if (!await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement())) if (!(await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement())).Succeeded)
{ {
return new ChallengeResult(); return new ChallengeResult();
} }
var filename = AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, id); var filename = AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, id);
FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename)); FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
if (!fi.Exists) return HttpNotFound(new { Error = "Professional signature not found" }); if (!fi.Exists) return NotFound(new { Error = "Professional signature not found" });
return File(fi.OpenRead(), "application/x-pdf", filename); ; return File(fi.OpenRead(), "application/x-pdf", filename); ;
} }
[HttpPost("clisign/{billingCode}/{id}")] [HttpPost("clisign/{billingCode}/{id}")]
public async Task<IActionResult> CliSign(string billingCode, long id) public async Task<IActionResult> CliSign(string billingCode, long id)
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var estimate = dbContext.Estimates.Include( e=>e.Query var estimate = dbContext.Estimates.Include( e=>e.Query
).Include(e=>e.Owner).Include(e=>e.Owner.Performer).Include(e=>e.Client) ).Include(e=>e.Owner).Include(e=>e.Owner.Performer).Include(e=>e.Client)
.FirstOrDefault( e=> e.Id == id && e.Query.ClientId == uid ); .FirstOrDefault( e=> e.Id == id && e.Query.ClientId == uid );
if (!await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement())) if (!(await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement())).Succeeded)
{ {
return new ChallengeResult(); return new ChallengeResult();
} }
@ -164,7 +161,7 @@ namespace Yavsc.ApiControllers
return new BadRequestResult(); return new BadRequestResult();
User.ReceiveProSignature(billingCode,id,Request.Form.Files[0],"cli"); User.ReceiveProSignature(billingCode,id,Request.Form.Files[0],"cli");
estimate.ClientValidationDate = DateTime.Now; estimate.ClientValidationDate = DateTime.Now;
dbContext.SaveChanges(_userManager.GetUserId(User)); dbContext.SaveChanges(User.GetUserId());
return Ok (new { ClientValidationDate = estimate.ClientValidationDate }); return Ok (new { ClientValidationDate = estimate.ClientValidationDate });
} }
@ -173,14 +170,14 @@ namespace Yavsc.ApiControllers
{ {
// For authorization purpose // For authorization purpose
var estimate = dbContext.Estimates.FirstOrDefault(e=>e.Id == id); var estimate = dbContext.Estimates.FirstOrDefault(e=>e.Id == id);
if (!await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement())) if (!(await authorizationService.AuthorizeAsync(User, estimate, new ViewRequirement())).Succeeded)
{ {
return new ChallengeResult(); return new ChallengeResult();
} }
var filename = AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, id); var filename = AbstractFileSystemHelpers.SignFileNameFormat("pro", billingCode, id);
FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename)); FileInfo fi = new FileInfo(Path.Combine(AbstractFileSystemHelpers.UserBillsDirName, filename));
if (!fi.Exists) return HttpNotFound(new { Error = "Professional signature not found" }); if (!fi.Exists) return NotFound(new { Error = "Professional signature not found" });
return File(fi.OpenRead(), "application/x-pdf", filename); ; return File(fi.OpenRead(), "application/x-pdf", filename); ;
} }
} }

@ -4,7 +4,6 @@ using System.Security.Claims;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Yavsc.Controllers namespace Yavsc.Controllers
@ -14,6 +13,8 @@ namespace Yavsc.Controllers
using Yavsc.Models.Workflow; using Yavsc.Models.Workflow;
using Yavsc.Models.Billing; using Yavsc.Models.Billing;
using Yavsc.Abstract.Identity; using Yavsc.Abstract.Identity;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
[Produces("application/json")] [Produces("application/json")]
[Route("api/bookquery"), Authorize(Roles = "Performer,Administrator")] [Route("api/bookquery"), Authorize(Roles = "Performer,Administrator")]
@ -37,7 +38,7 @@ namespace Yavsc.Controllers
[HttpGet] [HttpGet]
public IEnumerable<RdvQueryProviderInfo> GetCommands(long maxId=long.MaxValue) public IEnumerable<RdvQueryProviderInfo> GetCommands(long maxId=long.MaxValue)
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var now = DateTime.Now; var now = DateTime.Now;
var result = _context.RdvQueries.Include(c => c.Location). var result = _context.RdvQueries.Include(c => c.Location).
@ -69,15 +70,15 @@ namespace Yavsc.Controllers
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
RdvQuery bookQuery = _context.RdvQueries.Where(c => c.ClientId == uid || c.PerformerId == uid).Single(m => m.Id == id); RdvQuery bookQuery = _context.RdvQueries.Where(c => c.ClientId == uid || c.PerformerId == uid).Single(m => m.Id == id);
if (bookQuery == null) if (bookQuery == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(bookQuery); return Ok(bookQuery);
@ -89,28 +90,28 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != bookQuery.Id) if (id != bookQuery.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (bookQuery.ClientId != uid) if (bookQuery.ClientId != uid)
return StatusCode(404); return NotFound();
_context.Entry(bookQuery).State = EntityState.Modified; _context.Entry(bookQuery).State = EntityState.Modified;
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!BookQueryExists(id)) if (!BookQueryExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -118,7 +119,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/BookQueryApi // POST: api/BookQueryApi
@ -127,9 +128,9 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (bookQuery.ClientId != uid) if (bookQuery.ClientId != uid)
{ {
ModelState.AddModelError("ClientId", "You must be the client at creating a book query"); ModelState.AddModelError("ClientId", "You must be the client at creating a book query");
@ -138,13 +139,13 @@ namespace Yavsc.Controllers
_context.RdvQueries.Add(bookQuery); _context.RdvQueries.Add(bookQuery);
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (BookQueryExists(bookQuery.Id)) if (BookQueryExists(bookQuery.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -161,19 +162,19 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
RdvQuery bookQuery = _context.RdvQueries.Single(m => m.Id == id); RdvQuery bookQuery = _context.RdvQueries.Single(m => m.Id == id);
if (bookQuery == null) if (bookQuery == null)
{ {
return StatusCode(404); return NotFound();
} }
if (bookQuery.ClientId != uid) return StatusCode(404); if (bookQuery.ClientId != uid) return NotFound();
_context.RdvQueries.Remove(bookQuery); _context.RdvQueries.Remove(bookQuery);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(bookQuery); return Ok(bookQuery);
} }

@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Billing; using Yavsc.Models.Billing;
@ -26,22 +27,22 @@ namespace Yavsc.Controllers
bool UserIsAdminOrThis(string uid) bool UserIsAdminOrThis(string uid)
{ {
if (User.IsInRole(Constants.AdminGroupName)) return true; if (User.IsInRole(Constants.AdminGroupName)) return true;
return uid == _userManager.GetUserId(User); return uid == User.GetUserId();
} }
bool UserIsAdminOrInThese(string oid, string uid) bool UserIsAdminOrInThese(string oid, string uid)
{ {
if (User.IsInRole(Constants.AdminGroupName)) return true; if (User.IsInRole(Constants.AdminGroupName)) return true;
var cuid = _userManager.GetUserId(User); var cuid = User.GetUserId();
return cuid == uid || cuid == oid; return cuid == uid || cuid == oid;
} }
// GET: api/Estimate{?ownerId=_userManager.GetUserId(User)} // GET: api/Estimate{?ownerId=User.GetUserId()}
[HttpGet] [HttpGet]
public IActionResult GetEstimates(string ownerId = null) public IActionResult GetEstimates(string ownerId = null)
{ {
if (ownerId == null) ownerId = _userManager.GetUserId(User); if (ownerId == null) ownerId = User.GetUserId();
else if (!UserIsAdminOrThis(ownerId)) // throw new Exception("Not authorized") ; else if (!UserIsAdminOrThis(ownerId)) // throw new Exception("Not authorized") ;
// or just do nothing // or just do nothing
return new HttpStatusCodeResult(StatusCodes.Status403Forbidden); return new StatusCodeResult(StatusCodes.Status403Forbidden);
return Ok(_context.Estimates.Include(e => e.Bill).Where(e => e.OwnerId == ownerId)); return Ok(_context.Estimates.Include(e => e.Bill).Where(e => e.OwnerId == ownerId));
} }
// GET: api/Estimate/5 // GET: api/Estimate/5
@ -50,19 +51,19 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Estimate estimate = _context.Estimates.Include(e => e.Bill).Single(m => m.Id == id); Estimate estimate = _context.Estimates.Include(e => e.Bill).Single(m => m.Id == id);
if (estimate == null) if (estimate == null)
{ {
return StatusCode(404); return NotFound();
} }
if (UserIsAdminOrInThese(estimate.ClientId, estimate.OwnerId)) if (UserIsAdminOrInThese(estimate.ClientId, estimate.OwnerId))
return Ok(estimate); return Ok(estimate);
return new HttpStatusCodeResult(StatusCodes.Status403Forbidden); return new StatusCodeResult(StatusCodes.Status403Forbidden);
} }
// PUT: api/Estimate/5 // PUT: api/Estimate/5
@ -77,28 +78,28 @@ namespace Yavsc.Controllers
if (id != estimate.Id) if (id != estimate.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInRole(Constants.AdminGroupName)) if (!User.IsInRole(Constants.AdminGroupName))
{ {
if (uid != estimate.OwnerId) if (uid != estimate.OwnerId)
{ {
ModelState.AddModelError("OwnerId", "You can only modify your own estimates"); ModelState.AddModelError("OwnerId", "You can only modify your own estimates");
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
} }
var entry = _context.Attach(estimate); var entry = _context.Attach(estimate);
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!EstimateExists(id)) if (!EstimateExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -113,7 +114,7 @@ namespace Yavsc.Controllers
[HttpPost, Produces("application/json")] [HttpPost, Produces("application/json")]
public IActionResult PostEstimate([FromBody] Estimate estimate) public IActionResult PostEstimate([FromBody] Estimate estimate)
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (estimate.OwnerId == null) estimate.OwnerId = uid; if (estimate.OwnerId == null) estimate.OwnerId = uid;
if (!User.IsInRole(Constants.AdminGroupName)) if (!User.IsInRole(Constants.AdminGroupName))
@ -121,7 +122,7 @@ namespace Yavsc.Controllers
if (uid != estimate.OwnerId) if (uid != estimate.OwnerId)
{ {
ModelState.AddModelError("OwnerId", "You can only create your own estimates"); ModelState.AddModelError("OwnerId", "You can only create your own estimates");
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
} }
@ -130,10 +131,10 @@ namespace Yavsc.Controllers
var query = _context.RdvQueries.FirstOrDefault(q => q.Id == estimate.CommandId); var query = _context.RdvQueries.FirstOrDefault(q => q.Id == estimate.CommandId);
if (query == null) if (query == null)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
query.ValidationDate = DateTime.Now; query.ValidationDate = DateTime.Now;
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
_context.Entry(query).State = EntityState.Detached; _context.Entry(query).State = EntityState.Detached;
} }
if (!ModelState.IsValid) if (!ModelState.IsValid)
@ -153,13 +154,13 @@ namespace Yavsc.Controllers
*/ */
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (EstimateExists(estimate.Id)) if (EstimateExists(estimate.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -175,26 +176,26 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Estimate estimate = _context.Estimates.Include(e => e.Bill).Single(m => m.Id == id); Estimate estimate = _context.Estimates.Include(e => e.Bill).Single(m => m.Id == id);
if (estimate == null) if (estimate == null)
{ {
return StatusCode(404); return NotFound();
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInRole(Constants.AdminGroupName)) if (!User.IsInRole(Constants.AdminGroupName))
{ {
if (uid != estimate.OwnerId) if (uid != estimate.OwnerId)
{ {
ModelState.AddModelError("OwnerId", "You can only create your own estimates"); ModelState.AddModelError("OwnerId", "You can only create your own estimates");
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
} }
_context.Estimates.Remove(estimate); _context.Estimates.Remove(estimate);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(estimate); return Ok(estimate);
} }

@ -1,9 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Billing; using Yavsc.Models.Billing;
@ -24,7 +22,7 @@ namespace Yavsc.Controllers
[HttpGet] [HttpGet]
public IEnumerable<EstimateTemplate> GetEstimateTemplate() public IEnumerable<EstimateTemplate> GetEstimateTemplate()
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
return _context.EstimateTemplates.Where(x=>x.OwnerId==uid); return _context.EstimateTemplates.Where(x=>x.OwnerId==uid);
} }
@ -34,15 +32,15 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
EstimateTemplate estimateTemplate = _context.EstimateTemplates.Where(x=>x.OwnerId==uid).Single(m => m.Id == id); EstimateTemplate estimateTemplate = _context.EstimateTemplates.Where(x=>x.OwnerId==uid).Single(m => m.Id == id);
if (estimateTemplate == null) if (estimateTemplate == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(estimateTemplate); return Ok(estimateTemplate);
@ -54,29 +52,29 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != estimateTemplate.Id) if (id != estimateTemplate.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (estimateTemplate.OwnerId!=uid) if (estimateTemplate.OwnerId!=uid)
if (!User.IsInRole(Constants.AdminGroupName)) if (!User.IsInRole(Constants.AdminGroupName))
return new HttpStatusCodeResult(StatusCodes.Status403Forbidden); return new StatusCodeResult(StatusCodes.Status403Forbidden);
_context.Entry(estimateTemplate).State = EntityState.Modified; _context.Entry(estimateTemplate).State = EntityState.Modified;
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!EstimateTemplateExists(id)) if (!EstimateTemplateExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -84,7 +82,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/EstimateTemplatesApi // POST: api/EstimateTemplatesApi
@ -93,20 +91,20 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
estimateTemplate.OwnerId=_userManager.GetUserId(User); estimateTemplate.OwnerId=User.GetUserId();
_context.EstimateTemplates.Add(estimateTemplate); _context.EstimateTemplates.Add(estimateTemplate);
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (EstimateTemplateExists(estimateTemplate.Id)) if (EstimateTemplateExists(estimateTemplate.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -123,21 +121,21 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
EstimateTemplate estimateTemplate = _context.EstimateTemplates.Single(m => m.Id == id); EstimateTemplate estimateTemplate = _context.EstimateTemplates.Single(m => m.Id == id);
if (estimateTemplate == null) if (estimateTemplate == null)
{ {
return StatusCode(404); return NotFound();
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (estimateTemplate.OwnerId!=uid) if (estimateTemplate.OwnerId!=uid)
if (!User.IsInRole(Constants.AdminGroupName)) if (!User.IsInRole(Constants.AdminGroupName))
return new HttpStatusCodeResult(StatusCodes.Status403Forbidden); return new StatusCodeResult(StatusCodes.Status403Forbidden);
_context.EstimateTemplates.Remove(estimateTemplate); _context.EstimateTemplates.Remove(estimateTemplate);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(estimateTemplate); return Ok(estimateTemplate);
} }

@ -30,14 +30,27 @@ namespace Yavsc.ApiControllers
[HttpPost("query/reject")] [HttpPost("query/reject")]
public IActionResult RejectQuery(string billingCode, long queryId) public IActionResult RejectQuery(string billingCode, long queryId)
{ {
if (billingCode == null) return HttpBadRequest("billingCode"); if (billingCode == null) return BadRequest("billingCode");
if (queryId == 0) return HttpBadRequest("queryId"); if (queryId == 0) return BadRequest("queryId");
var billing = BillingService.GetBillable(dbContext, billingCode, queryId); var billing = BillingService.GetBillable(dbContext, billingCode, queryId);
if (billing == null) return HttpBadRequest(); if (billing == null) return BadRequest();
billing.Rejected = true; billing.Decided = true;
billing.RejectedAt = DateTime.Now; billing.Accepted = false;
dbContext.SaveChanges(); dbContext.SaveChanges();
return Ok(); return Ok();
} }
[HttpPost("query/reject")]
public IActionResult AcceptQuery(string billingCode, long queryId)
{
if (billingCode == null) return BadRequest("billingCode");
if (queryId == 0) return BadRequest("queryId");
var billing = BillingService.GetBillable(dbContext, billingCode, queryId);
if (billing == null) return BadRequest();
billing.Accepted = true;
billing.Decided = true;
dbContext.SaveChanges();
return Ok();
}
} }
} }

@ -1,6 +1,4 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json; using Newtonsoft.Json;
using Yavsc.Helpers; using Yavsc.Helpers;

@ -1,12 +1,11 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
using Microsoft.EntityFrameworkCore;
using Models; using Models;
using Yavsc.Helpers; using Yavsc.Helpers;
using Yavsc.Services; using Yavsc.Services;
@ -44,7 +43,7 @@ namespace Yavsc.Controllers
ModelState.AddModelError("id","Specifier un identifiant de prestataire valide"); ModelState.AddModelError("id","Specifier un identifiant de prestataire valide");
} }
else { else {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInRole("Administrator")) if (!User.IsInRole("Administrator"))
if (uid != id) return new ChallengeResult(); if (uid != id) return new ChallengeResult();

@ -1,10 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Market; using Yavsc.Models.Market;
@ -34,14 +31,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Product product = _context.Products.Single(m => m.Id == id); Product product = _context.Products.Single(m => m.Id == id);
if (product == null) if (product == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(product); return Ok(product);
@ -53,25 +50,25 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != product.Id) if (id != product.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(product).State = EntityState.Modified; _context.Entry(product).State = EntityState.Modified;
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!ProductExists(id)) if (!ProductExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -79,7 +76,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/ProductApi // POST: api/ProductApi
@ -88,19 +85,19 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Products.Add(product); _context.Products.Add(product);
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (ProductExists(product.Id)) if (ProductExists(product.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -117,17 +114,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Product product = _context.Products.Single(m => m.Id == id); Product product = _context.Products.Single(m => m.Id == id);
if (product == null) if (product == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.Products.Remove(product); _context.Products.Remove(product);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(product); return Ok(product);
} }

@ -1,11 +1,8 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Messaging; using Yavsc.Models.Messaging;
@ -26,7 +23,7 @@ namespace Yavsc.Controllers
[HttpGet] [HttpGet]
public IEnumerable<DimissClicked> GetDimissClicked() public IEnumerable<DimissClicked> GetDimissClicked()
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
return _context.DimissClicked.Where(d=>d.UserId == uid); return _context.DimissClicked.Where(d=>d.UserId == uid);
} }
@ -34,7 +31,7 @@ namespace Yavsc.Controllers
public async Task<IActionResult> Click(long noteid ) public async Task<IActionResult> Click(long noteid )
{ {
if (User.IsSignedIn()) if (User.IsSignedIn())
return await PostDimissClicked(new DimissClicked { NotificationId= noteid, UserId = _userManager.GetUserId(User)}); return await PostDimissClicked(new DimissClicked { NotificationId= noteid, UserId = User.GetUserId()});
await HttpContext.Session.LoadAsync(); await HttpContext.Session.LoadAsync();
var clicked = HttpContext.Session.GetString("clicked"); var clicked = HttpContext.Session.GetString("clicked");
if (clicked == null) { if (clicked == null) {
@ -47,19 +44,19 @@ namespace Yavsc.Controllers
[HttpGet("{id}", Name = "GetDimissClicked")] [HttpGet("{id}", Name = "GetDimissClicked")]
public async Task<IActionResult> GetDimissClicked([FromRoute] string id) public async Task<IActionResult> GetDimissClicked([FromRoute] string id)
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != id) return new ChallengeResult(); if (uid != id) return new ChallengeResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
DimissClicked dimissClicked = await _context.DimissClicked.SingleAsync(m => m.UserId == id); DimissClicked dimissClicked = await _context.DimissClicked.SingleAsync(m => m.UserId == id);
if (dimissClicked == null) if (dimissClicked == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(dimissClicked); return Ok(dimissClicked);
@ -69,30 +66,30 @@ namespace Yavsc.Controllers
[HttpPut("{id}")] [HttpPut("{id}")]
public async Task<IActionResult> PutDimissClicked([FromRoute] string id, [FromBody] DimissClicked dimissClicked) public async Task<IActionResult> PutDimissClicked([FromRoute] string id, [FromBody] DimissClicked dimissClicked)
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != id || uid != dimissClicked.UserId) return new ChallengeResult(); if (uid != id || uid != dimissClicked.UserId) return new ChallengeResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != dimissClicked.UserId) if (id != dimissClicked.UserId)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(dimissClicked).State = EntityState.Modified; _context.Entry(dimissClicked).State = EntityState.Modified;
try try
{ {
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!DimissClickedExists(id)) if (!DimissClickedExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -100,31 +97,31 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/DimissClicksApi // POST: api/DimissClicksApi
[HttpPost] [HttpPost]
public async Task<IActionResult> PostDimissClicked([FromBody] DimissClicked dimissClicked) public async Task<IActionResult> PostDimissClicked([FromBody] DimissClicked dimissClicked)
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != dimissClicked.UserId) return new ChallengeResult(); if (uid != dimissClicked.UserId) return new ChallengeResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.DimissClicked.Add(dimissClicked); _context.DimissClicked.Add(dimissClicked);
try try
{ {
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (DimissClickedExists(dimissClicked.UserId)) if (DimissClickedExists(dimissClicked.UserId))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -139,23 +136,23 @@ namespace Yavsc.Controllers
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeleteDimissClicked([FromRoute] string id) public async Task<IActionResult> DeleteDimissClicked([FromRoute] string id)
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!User.IsInRole("Administrator")) if (!User.IsInRole("Administrator"))
if (uid != id) return new ChallengeResult(); if (uid != id) return new ChallengeResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
DimissClicked dimissClicked = await _context.DimissClicked.SingleAsync(m => m.UserId == id); DimissClicked dimissClicked = await _context.DimissClicked.SingleAsync(m => m.UserId == id);
if (dimissClicked == null) if (dimissClicked == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.DimissClicked.Remove(dimissClicked); _context.DimissClicked.Remove(dimissClicked);
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
return Ok(dimissClicked); return Ok(dimissClicked);
} }

@ -1,10 +1,6 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Haircut; using Yavsc.Models.Haircut;
@ -34,14 +30,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
BrusherProfile brusherProfile = await _context.BrusherProfile.SingleAsync(m => m.UserId == id); BrusherProfile brusherProfile = await _context.BrusherProfile.SingleAsync(m => m.UserId == id);
if (brusherProfile == null) if (brusherProfile == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(brusherProfile); return Ok(brusherProfile);
@ -53,17 +49,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != brusherProfile.UserId) if (id != brusherProfile.UserId)
{ {
return HttpBadRequest(); return BadRequest();
} }
if (id != _userManager.GetUserId(User)) if (id != User.GetUserId())
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(brusherProfile).State = EntityState.Modified; _context.Entry(brusherProfile).State = EntityState.Modified;
@ -75,7 +71,7 @@ namespace Yavsc.Controllers
{ {
if (!BrusherProfileExists(id)) if (!BrusherProfileExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -83,7 +79,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/BursherProfilesApi // POST: api/BursherProfilesApi
@ -92,7 +88,7 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.BrusherProfile.Add(brusherProfile); _context.BrusherProfile.Add(brusherProfile);
@ -104,7 +100,7 @@ namespace Yavsc.Controllers
{ {
if (BrusherProfileExists(brusherProfile.UserId)) if (BrusherProfileExists(brusherProfile.UserId))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -121,13 +117,13 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
BrusherProfile brusherProfile = await _context.BrusherProfile.SingleAsync(m => m.UserId == id); BrusherProfile brusherProfile = await _context.BrusherProfile.SingleAsync(m => m.UserId == id);
if (brusherProfile == null) if (brusherProfile == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.BrusherProfile.Remove(brusherProfile); _context.BrusherProfile.Remove(brusherProfile);

@ -1,6 +1,5 @@
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
@ -16,14 +15,15 @@ namespace Yavsc.ApiControllers
using Models.Haircut; using Models.Haircut;
using System.Threading.Tasks; using System.Threading.Tasks;
using Helpers; using Helpers;
using Microsoft.EntityFrameworkCore;
using Models.Payment; using Models.Payment;
using Newtonsoft.Json; using Newtonsoft.Json;
using PayPal.PayPalAPIInterfaceService.Model; using PayPal.PayPalAPIInterfaceService.Model;
using Yavsc.Models.Haircut.Views; using Yavsc.Models.Haircut.Views;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;
[Route("api/haircut")] [Route("api/haircut")][Authorize]
public class HairCutController : Controller public class HairCutController : Controller
{ {
private readonly ApplicationDbContext _context; private readonly ApplicationDbContext _context;
@ -40,7 +40,9 @@ namespace Yavsc.ApiControllers
// user, as a client // user, as a client
public IActionResult Index() public IActionResult Index()
{ {
var uid = _userManager.GetUserId(User);
var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var now = DateTime.Now; var now = DateTime.Now;
var result = _context.HairCutQueries var result = _context.HairCutQueries
.Include(q => q.Prestation) .Include(q => q.Prestation)
@ -61,14 +63,14 @@ namespace Yavsc.ApiControllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
HairCutQuery hairCutQuery = await _context.HairCutQueries.SingleAsync(m => m.Id == id); HairCutQuery hairCutQuery = await _context.HairCutQueries.SingleAsync(m => m.Id == id);
if (hairCutQuery == null) if (hairCutQuery == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(hairCutQuery); return Ok(hairCutQuery);
@ -80,12 +82,12 @@ namespace Yavsc.ApiControllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != hairCutQuery.Id) if (id != hairCutQuery.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(hairCutQuery).State = EntityState.Modified; _context.Entry(hairCutQuery).State = EntityState.Modified;
@ -98,7 +100,7 @@ namespace Yavsc.ApiControllers
{ {
if (!HairCutQueryExists(id)) if (!HairCutQueryExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -106,20 +108,20 @@ namespace Yavsc.ApiControllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
[HttpPost] [HttpPost]
public async Task<IActionResult> PostQuery(HairCutQuery hairCutQuery) public async Task<IActionResult> PostQuery(HairCutQuery hairCutQuery)
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return new BadRequestObjectResult(ModelState); return new BadRequestObjectResult(ModelState);
} }
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.HairCutQueries.Add(hairCutQuery); _context.HairCutQueries.Add(hairCutQuery);
@ -131,7 +133,7 @@ namespace Yavsc.ApiControllers
{ {
if (HairCutQueryExists(hairCutQuery.Id)) if (HairCutQueryExists(hairCutQuery.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -159,13 +161,13 @@ namespace Yavsc.ApiControllers
} }
catch (Exception ex) { catch (Exception ex) {
_logger.LogError(ex.Message); _logger.LogError(ex.Message);
return new HttpStatusCodeResult(500); return new StatusCodeResult(500);
} }
if (payment==null) { if (payment==null) {
_logger.LogError("Error doing SetExpressCheckout, aborting."); _logger.LogError("Error doing SetExpressCheckout, aborting.");
_logger.LogError(JsonConvert.SerializeObject(Startup.PayPalSettings)); _logger.LogError(JsonConvert.SerializeObject(Config.PayPalSettings));
return new HttpStatusCodeResult(500); return new StatusCodeResult(500);
} }
switch (payment.Ack) switch (payment.Ack)
{ {
@ -174,11 +176,11 @@ namespace Yavsc.ApiControllers
{ {
var dbinfo = new PayPalPayment var dbinfo = new PayPalPayment
{ {
ExecutorId = _userManager.GetUserId(User), ExecutorId = User.GetUserId(),
CreationToken = payment.Token, CreationToken = payment.Token,
State = payment.Ack.ToString() State = payment.Ack.ToString()
}; };
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
} }
break; break;
@ -195,13 +197,13 @@ namespace Yavsc.ApiControllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
HairCutQuery hairCutQuery = await _context.HairCutQueries.SingleAsync(m => m.Id == id); HairCutQuery hairCutQuery = await _context.HairCutQueries.SingleAsync(m => m.Id == id);
if (hairCutQuery == null) if (hairCutQuery == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.HairCutQueries.Remove(hairCutQuery); _context.HairCutQueries.Remove(hairCutQuery);

@ -1,7 +1,3 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Models; using Yavsc.Models;
@ -33,14 +29,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
HyperLink hyperLink = await _context.HyperLink.SingleAsync(m => m.HRef == id); HyperLink hyperLink = await _context.HyperLink.SingleAsync(m => m.HRef == id);
if (hyperLink == null) if (hyperLink == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(hyperLink); return Ok(hyperLink);
@ -52,12 +48,12 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != hyperLink.HRef) if (id != hyperLink.HRef)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(hyperLink).State = EntityState.Modified; _context.Entry(hyperLink).State = EntityState.Modified;
@ -70,7 +66,7 @@ namespace Yavsc.Controllers
{ {
if (!HyperLinkExists(id)) if (!HyperLinkExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -78,7 +74,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/HyperLinkApi // POST: api/HyperLinkApi
@ -87,7 +83,7 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.HyperLink.Add(hyperLink); _context.HyperLink.Add(hyperLink);
@ -99,7 +95,7 @@ namespace Yavsc.Controllers
{ {
if (HyperLinkExists(hyperLink.HRef)) if (HyperLinkExists(hyperLink.HRef))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -116,13 +112,13 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
HyperLink hyperLink = await _context.HyperLink.SingleAsync(m => m.HRef == id); HyperLink hyperLink = await _context.HyperLink.SingleAsync(m => m.HRef == id);
if (hyperLink == null) if (hyperLink == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.HyperLink.Remove(hyperLink); _context.HyperLink.Remove(hyperLink);

@ -1,8 +1,4 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Models; using Yavsc.Models;
@ -35,14 +31,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Id == id); GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Id == id);
if (gitRepositoryReference == null) if (gitRepositoryReference == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(gitRepositoryReference); return Ok(gitRepositoryReference);
@ -54,7 +50,7 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Entry(gitRepositoryReference).State = EntityState.Modified; _context.Entry(gitRepositoryReference).State = EntityState.Modified;
@ -67,7 +63,7 @@ namespace Yavsc.Controllers
{ {
if (!GitRepositoryReferenceExists(id)) if (!GitRepositoryReferenceExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -75,7 +71,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/GitRefsApi // POST: api/GitRefsApi
@ -84,7 +80,7 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.GitRepositoryReference.Add(gitRepositoryReference); _context.GitRepositoryReference.Add(gitRepositoryReference);
@ -96,7 +92,7 @@ namespace Yavsc.Controllers
{ {
if (GitRepositoryReferenceExists(gitRepositoryReference.Id)) if (GitRepositoryReferenceExists(gitRepositoryReference.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -113,13 +109,13 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Id == id); GitRepositoryReference gitRepositoryReference = await _context.GitRepositoryReference.SingleAsync(m => m.Id == id);
if (gitRepositoryReference == null) if (gitRepositoryReference == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.GitRepositoryReference.Remove(gitRepositoryReference); _context.GitRepositoryReference.Remove(gitRepositoryReference);

@ -1,13 +1,8 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Server.Models.EMailing; using Yavsc.Server.Models.EMailing;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using System.Security.Claims; using Microsoft.EntityFrameworkCore;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
@ -36,14 +31,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id); MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
if (mailingTemplate == null) if (mailingTemplate == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(mailingTemplate); return Ok(mailingTemplate);
@ -55,12 +50,12 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != mailingTemplate.Id) if (id != mailingTemplate.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(mailingTemplate).State = EntityState.Modified; _context.Entry(mailingTemplate).State = EntityState.Modified;
@ -73,7 +68,7 @@ namespace Yavsc.Controllers
{ {
if (!MailingTemplateExists(id)) if (!MailingTemplateExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -81,7 +76,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/MailingTemplateApi // POST: api/MailingTemplateApi
@ -90,7 +85,7 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.MailingTemplate.Add(mailingTemplate); _context.MailingTemplate.Add(mailingTemplate);
@ -102,7 +97,7 @@ namespace Yavsc.Controllers
{ {
if (MailingTemplateExists(mailingTemplate.Id)) if (MailingTemplateExists(mailingTemplate.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -119,13 +114,13 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id); MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
if (mailingTemplate == null) if (mailingTemplate == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.MailingTemplate.Remove(mailingTemplate); _context.MailingTemplate.Remove(mailingTemplate);

@ -1,9 +1,6 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Musical; using Yavsc.Models.Musical;
@ -33,14 +30,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
MusicalPreference musicalPreference = _context.MusicalPreference.Single(m => m.OwnerProfileId == id); MusicalPreference musicalPreference = _context.MusicalPreference.Single(m => m.OwnerProfileId == id);
if (musicalPreference == null) if (musicalPreference == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(musicalPreference); return Ok(musicalPreference);
@ -51,25 +48,25 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != musicalPreference.OwnerProfileId) if (id != musicalPreference.OwnerProfileId)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(musicalPreference).State = EntityState.Modified; _context.Entry(musicalPreference).State = EntityState.Modified;
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!MusicalPreferenceExists(id)) if (!MusicalPreferenceExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -77,7 +74,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/MusicalPreferencesApi // POST: api/MusicalPreferencesApi
@ -86,19 +83,19 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.MusicalPreference.Add(musicalPreference); _context.MusicalPreference.Add(musicalPreference);
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (MusicalPreferenceExists(musicalPreference.OwnerProfileId)) if (MusicalPreferenceExists(musicalPreference.OwnerProfileId))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -115,17 +112,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
MusicalPreference musicalPreference = _context.MusicalPreference.Single(m => m.OwnerProfileId == id); MusicalPreference musicalPreference = _context.MusicalPreference.Single(m => m.OwnerProfileId == id);
if (musicalPreference == null) if (musicalPreference == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.MusicalPreference.Remove(musicalPreference); _context.MusicalPreference.Remove(musicalPreference);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(musicalPreference); return Ok(musicalPreference);
} }

@ -1,9 +1,6 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Musical; using Yavsc.Models.Musical;
@ -33,14 +30,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id); MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id);
if (musicalTendency == null) if (musicalTendency == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(musicalTendency); return Ok(musicalTendency);
@ -52,25 +49,25 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != musicalTendency.Id) if (id != musicalTendency.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(musicalTendency).State = EntityState.Modified; _context.Entry(musicalTendency).State = EntityState.Modified;
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!MusicalTendencyExists(id)) if (!MusicalTendencyExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -78,7 +75,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/MusicalTendenciesApi // POST: api/MusicalTendenciesApi
@ -87,19 +84,19 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.MusicalTendency.Add(musicalTendency); _context.MusicalTendency.Add(musicalTendency);
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (MusicalTendencyExists(musicalTendency.Id)) if (MusicalTendencyExists(musicalTendency.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -116,17 +113,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id); MusicalTendency musicalTendency = _context.MusicalTendency.Single(m => m.Id == id);
if (musicalTendency == null) if (musicalTendency == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.MusicalTendency.Remove(musicalTendency); _context.MusicalTendency.Remove(musicalTendency);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(musicalTendency); return Ok(musicalTendency);
} }

@ -5,6 +5,7 @@ using System.Security.Claims;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Identity; using Yavsc.Models.Identity;
@ -30,7 +31,7 @@ public class NativeConfidentialController : Controller
public IActionResult Register( public IActionResult Register(
[FromBody] DeviceDeclaration declaration) [FromBody] DeviceDeclaration declaration)
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
@ -40,31 +41,29 @@ public class NativeConfidentialController : Controller
declaration.LatestActivityUpdate = DateTime.Now; declaration.LatestActivityUpdate = DateTime.Now;
_logger.LogInformation($"Registering device with id:{declaration.DeviceId} for {uid}"); _logger.LogInformation($"Registering device with id:{declaration.DeviceId} for {uid}");
var alreadyRegisteredDevice = _context.DeviceDeclaration.FirstOrDefault(d => d.DeviceId == declaration.DeviceId); DeviceDeclaration? alreadyRegisteredDevice = _context.DeviceDeclaration.FirstOrDefault(d => d.DeviceId == declaration.DeviceId);
var deviceAlreadyRegistered = (alreadyRegisteredDevice!=null); var deviceAlreadyRegistered = (alreadyRegisteredDevice!=null);
if (deviceAlreadyRegistered) if (alreadyRegisteredDevice==null)
{ {
_logger.LogInformation($"deviceAlreadyRegistered"); declaration.DeclarationDate = DateTime.Now;
// Override an exiting owner declaration.DeviceOwnerId = uid;
_context.DeviceDeclaration.Add(declaration);
}
else {
alreadyRegisteredDevice.DeviceOwnerId = uid; alreadyRegisteredDevice.DeviceOwnerId = uid;
alreadyRegisteredDevice.Model = declaration.Model; alreadyRegisteredDevice.Model = declaration.Model;
alreadyRegisteredDevice.Platform = declaration.Platform; alreadyRegisteredDevice.Platform = declaration.Platform;
alreadyRegisteredDevice.Version = declaration.Version; alreadyRegisteredDevice.Version = declaration.Version;
_context.Update(alreadyRegisteredDevice); _context.Update(alreadyRegisteredDevice);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
}
else
{
_logger.LogInformation($"new device");
declaration.DeclarationDate = DateTime.Now;
declaration.DeviceOwnerId = uid;
_context.DeviceDeclaration.Add(declaration as DeviceDeclaration);
_context.SaveChanges(_userManager.GetUserId(User));
} }
_context.SaveChanges(User.GetUserId());
var latestActivityUpdate = _context.Activities.Max(a=>a.DateModified); var latestActivityUpdate = _context.Activities.Max(a=>a.DateModified);
return Json(new { return Json(new {
IsAnUpdate = deviceAlreadyRegistered, IsAnUpdate = deviceAlreadyRegistered,
UpdateActivities = (latestActivityUpdate != declaration.LatestActivityUpdate) UpdateActivities = latestActivityUpdate != declaration.LatestActivityUpdate
}); });
} }

@ -2,6 +2,7 @@ using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
namespace Yavsc.Controllers namespace Yavsc.Controllers
@ -23,23 +24,23 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Models.Blog.BlogPost blogpost = _context.Blogspot.Single(x=>x.Id == id); Models.Blog.BlogPost blogpost = _context.Blogspot.Single(x=>x.Id == id);
if (blogpost == null) if (blogpost == null)
{ {
return StatusCode(404); return NotFound();
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (blogpost.AuthorId!=uid) if (blogpost.AuthorId!=uid)
if (!User.IsInRole(Constants.AdminGroupName)) if (!User.IsInRole(Constants.AdminGroupName))
return HttpBadRequest(); return BadRequest();
blogpost.Rate = rate; blogpost.Rate = rate;
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(); return Ok();
} }

@ -1,10 +1,8 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Access; using Yavsc.Models.Access;
@ -34,22 +32,22 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
BlackListed blackListed = _context.BlackListed.Single(m => m.Id == id); BlackListed blackListed = _context.BlackListed.Single(m => m.Id == id);
if (blackListed == null) if (blackListed == null)
{ {
return StatusCode(404); return NotFound();
} }
if (!CheckPermission(blackListed)) if (!CheckPermission(blackListed))
return HttpBadRequest(); return BadRequest();
return Ok(blackListed); return Ok(blackListed);
} }
private bool CheckPermission(BlackListed blackListed) private bool CheckPermission(BlackListed blackListed)
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != blackListed.OwnerId) if (uid != blackListed.OwnerId)
if (!User.IsInRole(Constants.AdminGroupName)) if (!User.IsInRole(Constants.AdminGroupName))
if (!User.IsInRole(Constants.FrontOfficeGroupName)) if (!User.IsInRole(Constants.FrontOfficeGroupName))
@ -62,26 +60,26 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != blackListed.Id) if (id != blackListed.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
if (!CheckPermission(blackListed)) if (!CheckPermission(blackListed))
return HttpBadRequest(); return BadRequest();
_context.Entry(blackListed).State = EntityState.Modified; _context.Entry(blackListed).State = EntityState.Modified;
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!BlackListedExists(id)) if (!BlackListedExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -89,7 +87,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/BlackListApi // POST: api/BlackListApi
@ -98,22 +96,22 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (!CheckPermission(blackListed)) if (!CheckPermission(blackListed))
return HttpBadRequest(); return BadRequest();
_context.BlackListed.Add(blackListed); _context.BlackListed.Add(blackListed);
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (BlackListedExists(blackListed.Id)) if (BlackListedExists(blackListed.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -130,20 +128,20 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
BlackListed blackListed = _context.BlackListed.Single(m => m.Id == id); BlackListed blackListed = _context.BlackListed.Single(m => m.Id == id);
if (blackListed == null) if (blackListed == null)
{ {
return StatusCode(404); return NotFound();
} }
if (!CheckPermission(blackListed)) if (!CheckPermission(blackListed))
return HttpBadRequest(); return BadRequest();
_context.BlackListed.Remove(blackListed); _context.BlackListed.Remove(blackListed);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(blackListed); return Ok(blackListed);
} }

@ -1,10 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Access; using Yavsc.Models.Access;
@ -34,15 +31,15 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
CircleAuthorizationToBlogPost circleAuthorizationToBlogPost = await _context.CircleAuthorizationToBlogPost.SingleAsync( CircleAuthorizationToBlogPost circleAuthorizationToBlogPost = await _context.CircleAuthorizationToBlogPost.SingleAsync(
m => m.CircleId == id && m.Allowed.OwnerId == uid ); m => m.CircleId == id && m.Allowed.OwnerId == uid );
if (circleAuthorizationToBlogPost == null) if (circleAuthorizationToBlogPost == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(circleAuthorizationToBlogPost); return Ok(circleAuthorizationToBlogPost);
@ -54,12 +51,12 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != circleAuthorizationToBlogPost.CircleId) if (id != circleAuthorizationToBlogPost.CircleId)
{ {
return HttpBadRequest(); return BadRequest();
} }
if (!CheckOwner(circleAuthorizationToBlogPost.CircleId)) if (!CheckOwner(circleAuthorizationToBlogPost.CircleId))
@ -70,13 +67,13 @@ namespace Yavsc.Controllers
try try
{ {
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!CircleAuthorizationToBlogPostExists(id)) if (!CircleAuthorizationToBlogPostExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -84,12 +81,12 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
private bool CheckOwner (long circleId) private bool CheckOwner (long circleId)
{ {
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var circle = _context.Circle.First(c=>c.Id==circleId); var circle = _context.Circle.First(c=>c.Id==circleId);
_context.Entry(circle).State = EntityState.Detached; _context.Entry(circle).State = EntityState.Detached;
return (circle.OwnerId == uid); return (circle.OwnerId == uid);
@ -100,7 +97,7 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (!CheckOwner(circleAuthorizationToBlogPost.CircleId)) if (!CheckOwner(circleAuthorizationToBlogPost.CircleId))
{ {
@ -109,13 +106,13 @@ namespace Yavsc.Controllers
_context.CircleAuthorizationToBlogPost.Add(circleAuthorizationToBlogPost); _context.CircleAuthorizationToBlogPost.Add(circleAuthorizationToBlogPost);
try try
{ {
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (CircleAuthorizationToBlogPostExists(circleAuthorizationToBlogPost.CircleId)) if (CircleAuthorizationToBlogPostExists(circleAuthorizationToBlogPost.CircleId))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -132,9 +129,9 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
CircleAuthorizationToBlogPost circleAuthorizationToBlogPost = await _context.CircleAuthorizationToBlogPost.Include( CircleAuthorizationToBlogPost circleAuthorizationToBlogPost = await _context.CircleAuthorizationToBlogPost.Include(
a=>a.Allowed a=>a.Allowed
@ -142,10 +139,10 @@ namespace Yavsc.Controllers
&& m.Allowed.OwnerId == uid); && m.Allowed.OwnerId == uid);
if (circleAuthorizationToBlogPost == null) if (circleAuthorizationToBlogPost == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.CircleAuthorizationToBlogPost.Remove(circleAuthorizationToBlogPost); _context.CircleAuthorizationToBlogPost.Remove(circleAuthorizationToBlogPost);
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
return Ok(circleAuthorizationToBlogPost); return Ok(circleAuthorizationToBlogPost);
} }

@ -1,13 +1,10 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.ViewModels.Chat; using Yavsc.ViewModels.Chat;
using Yavsc.Services; using Yavsc.Services;
using Microsoft.EntityFrameworkCore;
namespace Yavsc.Controllers namespace Yavsc.Controllers
{ {
@ -72,12 +69,12 @@ namespace Yavsc.Controllers
if (!ModelState.IsValid) if (!ModelState.IsValid)
// Miguel mech profiler // Miguel mech profiler
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var user = dbContext.ApplicationUser.Include(u => u.Connections).FirstOrDefault(u => u.UserName == userName); var user = dbContext.ApplicationUser.Include(u => u.Connections).FirstOrDefault(u => u.UserName == userName);
if (user == null) return StatusCode(404); if (user == null) return NotFound();
return Ok(new ChatUserInfo return Ok(new ChatUserInfo
{ {

@ -1,9 +1,5 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Models; using Yavsc.Models;
@ -35,7 +31,7 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
ChatRoomAccess chatRoomAccess = await _context.ChatRoomAccess.SingleAsync(m => m.ChannelName == id); ChatRoomAccess chatRoomAccess = await _context.ChatRoomAccess.SingleAsync(m => m.ChannelName == id);
@ -44,16 +40,16 @@ namespace Yavsc.Controllers
if (chatRoomAccess == null) if (chatRoomAccess == null)
{ {
return StatusCode(404); return NotFound();
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid != chatRoomAccess.UserId && uid != chatRoomAccess.Room.OwnerId if (uid != chatRoomAccess.UserId && uid != chatRoomAccess.Room.OwnerId
&& ! User.IsInRole(Constants.AdminGroupName)) && ! User.IsInRole(Constants.AdminGroupName))
{ {
ModelState.AddModelError("UserId","get refused"); ModelState.AddModelError("UserId","get refused");
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
return Ok(chatRoomAccess); return Ok(chatRoomAccess);
@ -65,20 +61,20 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (id != chatRoomAccess.ChannelName) if (id != chatRoomAccess.ChannelName)
{ {
return HttpBadRequest(); return BadRequest();
} }
var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName ); var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName );
if (uid != room.OwnerId && ! User.IsInRole(Constants.AdminGroupName)) if (uid != room.OwnerId && ! User.IsInRole(Constants.AdminGroupName))
{ {
ModelState.AddModelError("ChannelName", "access put refused"); ModelState.AddModelError("ChannelName", "access put refused");
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Entry(chatRoomAccess).State = EntityState.Modified; _context.Entry(chatRoomAccess).State = EntityState.Modified;
@ -91,7 +87,7 @@ namespace Yavsc.Controllers
{ {
if (!ChatRoomAccessExists(id)) if (!ChatRoomAccessExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -99,7 +95,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/ChatRoomAccessApi // POST: api/ChatRoomAccessApi
@ -108,15 +104,15 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName ); var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName );
if (room == null || (uid != room.OwnerId && ! User.IsInRole(Constants.AdminGroupName))) if (room == null || (uid != room.OwnerId && ! User.IsInRole(Constants.AdminGroupName)))
{ {
ModelState.AddModelError("ChannelName", "access post refused"); ModelState.AddModelError("ChannelName", "access post refused");
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.ChatRoomAccess.Add(chatRoomAccess); _context.ChatRoomAccess.Add(chatRoomAccess);
@ -129,7 +125,7 @@ namespace Yavsc.Controllers
{ {
if (ChatRoomAccessExists(chatRoomAccess.ChannelName)) if (ChatRoomAccessExists(chatRoomAccess.ChannelName))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -146,21 +142,21 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
ChatRoomAccess chatRoomAccess = await _context.ChatRoomAccess.Include(acc => acc.Room).SingleAsync(m => m.ChannelName == id); ChatRoomAccess chatRoomAccess = await _context.ChatRoomAccess.Include(acc => acc.Room).SingleAsync(m => m.ChannelName == id);
if (chatRoomAccess == null) if (chatRoomAccess == null)
{ {
return StatusCode(404); return NotFound();
} }
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName ); var room = _context.ChatRoom.First(channel => channel.Name == chatRoomAccess.ChannelName );
if (room == null || (uid != room.OwnerId && chatRoomAccess.UserId != uid && ! User.IsInRole(Constants.AdminGroupName))) if (room == null || (uid != room.OwnerId && chatRoomAccess.UserId != uid && ! User.IsInRole(Constants.AdminGroupName)))
{ {
ModelState.AddModelError("UserId", "access drop refused"); ModelState.AddModelError("UserId", "access drop refused");
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.ChatRoomAccess.Remove(chatRoomAccess); _context.ChatRoomAccess.Remove(chatRoomAccess);

@ -1,10 +1,6 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Chat; using Yavsc.Models.Chat;
@ -34,14 +30,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
ChatRoom chatRoom = await _context.ChatRoom.SingleAsync(m => m.Name == id); ChatRoom chatRoom = await _context.ChatRoom.SingleAsync(m => m.Name == id);
if (chatRoom == null) if (chatRoom == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(chatRoom); return Ok(chatRoom);
@ -53,17 +49,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != chatRoom.Name) if (id != chatRoom.Name)
{ {
return HttpBadRequest(); return BadRequest();
} }
if (_userManager.GetUserId(User) != chatRoom.OwnerId ) if (User.GetUserId() != chatRoom.OwnerId )
{ {
return HttpBadRequest(new {error = "OwnerId"}); return BadRequest(new {error = "OwnerId"});
} }
_context.Entry(chatRoom).State = EntityState.Modified; _context.Entry(chatRoom).State = EntityState.Modified;
@ -76,7 +72,7 @@ namespace Yavsc.Controllers
{ {
if (!ChatRoomExists(id)) if (!ChatRoomExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -84,7 +80,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/ChatRoomApi // POST: api/ChatRoomApi
@ -93,12 +89,12 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (_userManager.GetUserId(User) != chatRoom.OwnerId ) if (User.GetUserId() != chatRoom.OwnerId )
{ {
return HttpBadRequest(new {error = "OwnerId"}); return BadRequest(new {error = "OwnerId"});
} }
_context.ChatRoom.Add(chatRoom); _context.ChatRoom.Add(chatRoom);
@ -110,7 +106,7 @@ namespace Yavsc.Controllers
{ {
if (ChatRoomExists(chatRoom.Name)) if (ChatRoomExists(chatRoom.Name))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -127,7 +123,7 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
ChatRoom chatRoom = await _context.ChatRoom.SingleAsync(m => m.Name == id); ChatRoom chatRoom = await _context.ChatRoom.SingleAsync(m => m.Name == id);
@ -135,13 +131,13 @@ namespace Yavsc.Controllers
if (chatRoom == null) if (chatRoom == null)
{ {
return StatusCode(404); return NotFound();
} }
if (_userManager.GetUserId(User) != chatRoom.OwnerId ) if (User.GetUserId() != chatRoom.OwnerId )
{ {
if (!User.IsInRole(Constants.AdminGroupName)) if (!User.IsInRole(Constants.AdminGroupName))
return HttpBadRequest(new {error = "OwnerId"}); return BadRequest(new {error = "OwnerId"});
} }
_context.ChatRoom.Remove(chatRoom); _context.ChatRoom.Remove(chatRoom);

@ -1,10 +1,6 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Relationship; using Yavsc.Models.Relationship;
@ -34,14 +30,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Circle circle = await _context.Circle.SingleAsync(m => m.Id == id); Circle circle = await _context.Circle.SingleAsync(m => m.Id == id);
if (circle == null) if (circle == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(circle); return Ok(circle);
@ -53,25 +49,25 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != circle.Id) if (id != circle.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(circle).State = EntityState.Modified; _context.Entry(circle).State = EntityState.Modified;
try try
{ {
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!CircleExists(id)) if (!CircleExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -79,7 +75,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/CircleApi // POST: api/CircleApi
@ -88,19 +84,19 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Circle.Add(circle); _context.Circle.Add(circle);
try try
{ {
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (CircleExists(circle.Id)) if (CircleExists(circle.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -117,17 +113,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Circle circle = await _context.Circle.SingleAsync(m => m.Id == id); Circle circle = await _context.Circle.SingleAsync(m => m.Id == id);
if (circle == null) if (circle == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.Circle.Remove(circle); _context.Circle.Remove(circle);
await _context.SaveChangesAsync(_userManager.GetUserId(User)); await _context.SaveChangesAsync(User.GetUserId());
return Ok(circle); return Ok(circle);
} }

@ -1,9 +1,7 @@
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Abstract.Identity; using Yavsc.Abstract.Identity;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
namespace Yavsc.Controllers namespace Yavsc.Controllers
@ -32,25 +30,25 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != clientProviderInfo.UserId) if (id != clientProviderInfo.UserId)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(clientProviderInfo).State = EntityState.Modified; _context.Entry(clientProviderInfo).State = EntityState.Modified;
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!ClientProviderInfoExists(id)) if (!ClientProviderInfoExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -58,7 +56,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/ContactsApi // POST: api/ContactsApi
@ -67,19 +65,19 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.ClientProviderInfo.Add(clientProviderInfo); _context.ClientProviderInfo.Add(clientProviderInfo);
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (ClientProviderInfoExists(clientProviderInfo.UserId)) if (ClientProviderInfoExists(clientProviderInfo.UserId))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -96,17 +94,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
ClientProviderInfo clientProviderInfo = _context.ClientProviderInfo.Single(m => m.UserId == id); ClientProviderInfo clientProviderInfo = _context.ClientProviderInfo.Single(m => m.UserId == id);
if (clientProviderInfo == null) if (clientProviderInfo == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.ClientProviderInfo.Remove(clientProviderInfo); _context.ClientProviderInfo.Remove(clientProviderInfo);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(clientProviderInfo); return Ok(clientProviderInfo);
} }

@ -1,10 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.Market; using Yavsc.Models.Market;
@ -34,14 +31,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Service service = _context.Services.Single(m => m.Id == id); Service service = _context.Services.Single(m => m.Id == id);
if (service == null) if (service == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(service); return Ok(service);
@ -53,25 +50,25 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != service.Id) if (id != service.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(service).State = EntityState.Modified; _context.Entry(service).State = EntityState.Modified;
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!ServiceExists(id)) if (!ServiceExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -79,7 +76,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/ServiceApi // POST: api/ServiceApi
@ -88,19 +85,19 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Services.Add(service); _context.Services.Add(service);
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (ServiceExists(service.Id)) if (ServiceExists(service.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -117,17 +114,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Service service = _context.Services.Single(m => m.Id == id); Service service = _context.Services.Single(m => m.Id == id);
if (service == null) if (service == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.Services.Remove(service); _context.Services.Remove(service);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(service); return Ok(service);
} }

@ -1,14 +1,9 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Models.IT.Fixing; using Yavsc.Models.IT.Fixing;
using Microsoft.EntityFrameworkCore;
namespace Yavsc.ApiControllers namespace Yavsc.ApiControllers
{ {
@ -73,14 +68,14 @@ namespace Yavsc.ApiControllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Bug bug = await _context.Bug.SingleAsync(m => m.Id == id); Bug bug = await _context.Bug.SingleAsync(m => m.Id == id);
if (bug == null) if (bug == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(bug); return Ok(bug);
@ -92,12 +87,12 @@ namespace Yavsc.ApiControllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != bug.Id) if (id != bug.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(bug).State = EntityState.Modified; _context.Entry(bug).State = EntityState.Modified;
@ -110,7 +105,7 @@ namespace Yavsc.ApiControllers
{ {
if (!BugExists(id)) if (!BugExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -118,7 +113,7 @@ namespace Yavsc.ApiControllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/bug // POST: api/bug
@ -127,7 +122,7 @@ namespace Yavsc.ApiControllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Bug.Add(bug); _context.Bug.Add(bug);
@ -139,7 +134,7 @@ namespace Yavsc.ApiControllers
{ {
if (BugExists(bug.Id)) if (BugExists(bug.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -156,13 +151,13 @@ namespace Yavsc.ApiControllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
Bug bug = await _context.Bug.SingleAsync(m => m.Id == id); Bug bug = await _context.Bug.SingleAsync(m => m.Id == id);
if (bug == null) if (bug == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.Bug.Remove(bug); _context.Bug.Remove(bug);

@ -1,25 +1,21 @@
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Models.Account;
using Yavsc.ViewModels.Account;
using Yavsc.Helpers;
using Yavsc.Abstract.Identity;
namespace Yavsc.WebApi.Controllers namespace Yavsc.WebApi.Controllers
{ {
using Models;
using Models.Account;
using ViewModels.Account;
using Yavsc.Helpers;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity.EntityFramework;
using Yavsc.Abstract.Identity;
[Authorize(),Route("~/api/account")] [Authorize(),Route("~/api/account")]
public class ApiAccountController : Controller public class ApiAccountController : Controller
{ {
private UserManager<ApplicationUser> _userManager; private UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager; private readonly SignInManager<ApplicationUser> _signInManager;
readonly ApplicationDbContext _dbContext; readonly ApplicationDbContext _dbContext;
@ -54,7 +50,7 @@ namespace Yavsc.WebApi.Controllers
{ {
return new BadRequestObjectResult(ModelState); return new BadRequestObjectResult(ModelState);
} }
var user = await _userManager.FindByIdAsync(_userManager.GetUserId(User)); var user = await _userManager.FindByIdAsync(User.GetUserId());
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) {
IdentityResult result = await UserManager.ChangePasswordAsync(user, model.OldPassword, IdentityResult result = await UserManager.ChangePasswordAsync(user, model.OldPassword,
model.NewPassword); model.NewPassword);
@ -76,7 +72,7 @@ namespace Yavsc.WebApi.Controllers
{ {
return new BadRequestObjectResult(ModelState); return new BadRequestObjectResult(ModelState);
} }
var user = await _userManager.FindByIdAsync(_userManager.GetUserId(User)); var user = await _userManager.FindByIdAsync(User.GetUserId());
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) {
IdentityResult result = await UserManager.AddPasswordAsync(user, model.NewPassword); IdentityResult result = await UserManager.AddPasswordAsync(user, model.NewPassword);
if (!result.Succeeded) if (!result.Succeeded)
@ -132,12 +128,11 @@ namespace Yavsc.WebApi.Controllers
if (User==null) if (User==null)
return new BadRequestObjectResult( return new BadRequestObjectResult(
new { error = "user not found" }); new { error = "user not found" });
var uid = _userManager.GetUserId(User); var uid = User.FindFirstValue(ClaimTypes.NameIdentifier);
var userData = await _dbContext.Users var userData = await _dbContext.Users
.Include(u=>u.PostalAddress) .Include(u=>u.PostalAddress)
.Include(u=>u.AccountBalance) .Include(u=>u.AccountBalance)
.Include(u=>u.Roles)
.FirstAsync(u=>u.Id == uid); .FirstAsync(u=>u.Id == uid);
var user = new Yavsc.Models.Auth.Me(userData.Id, userData.UserName, userData.Email, var user = new Yavsc.Models.Auth.Me(userData.Id, userData.UserName, userData.Email,
@ -169,7 +164,7 @@ namespace Yavsc.WebApi.Controllers
{ {
if (!ModelState.IsValid) return new BadRequestObjectResult( if (!ModelState.IsValid) return new BadRequestObjectResult(
new { error = "Specify some valid user update request." }); new { error = "Specify some valid user update request." });
var user = await _userManager.FindByIdAsync(_userManager.GetUserId(User)); var user = await _userManager.FindByIdAsync(User.GetUserId());
var result = await _userManager.SetUserNameAsync(user, me.UserName); var result = await _userManager.SetUserNameAsync(user, me.UserName);
if (result.Succeeded) if (result.Succeeded)
return Ok(); return Ok();
@ -183,7 +178,7 @@ namespace Yavsc.WebApi.Controllers
public async Task<IActionResult> SetAvatar() public async Task<IActionResult> SetAvatar()
{ {
var root = User.InitPostToFileSystem(null); var root = User.InitPostToFileSystem(null);
var user = await _userManager.FindByIdAsync(_userManager.GetUserId(User)); var user = await _userManager.FindByIdAsync(User.GetUserId());
if (Request.Form.Files.Count!=1) if (Request.Form.Files.Count!=1)
return new BadRequestResult(); return new BadRequestResult();
var info = user.ReceiveAvatar(Request.Form.Files[0]); var info = user.ReceiveAvatar(Request.Form.Files[0]);

@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Yavsc.Abstract.Identity; using Yavsc.Abstract.Identity;
using Yavsc.Helpers;
using Yavsc.Models; using Yavsc.Models;
namespace Yavsc.Controllers namespace Yavsc.Controllers
@ -23,20 +24,20 @@ namespace Yavsc.Controllers
// GET: api/ApplicationUserApi // GET: api/ApplicationUserApi
[HttpGet] [HttpGet]
public IEnumerable<UserInfo> GetApplicationUser() public IEnumerable<UserInfo> GetApplicationUser(int skip=0, int take = 25)
{ {
return _context.Users.OrderByDescending(u => u.DateModified).Take(25) return _context.Users.Skip(skip).Take(take)
.Select(u=> new UserInfo { .Select(u=> new UserInfo{
UserId = u.Id, UserId = u.Id,
UserName = u.UserName, UserName = u.UserName,
Avatar = u.Avatar }); Avatar = u.Avatar});
} }
[HttpGet("search/{pattern}")] [HttpGet("search/{pattern}")]
public IEnumerable<UserInfo> SearchApplicationUser(string pattern) public IEnumerable<UserInfo> SearchApplicationUser(string pattern, int skip=0, int take = 25)
{ {
return _context.Users.Where(u => u.UserName.Contains(pattern)) return _context.Users.Where(u => u.UserName.Contains(pattern))
.OrderByDescending(u => u.DateModified).Take(25) .Skip(skip).Take(take)
.Select(u=> new UserInfo { .Select(u=> new UserInfo {
UserId = u.Id, UserId = u.Id,
UserName = u.UserName, UserName = u.UserName,
@ -49,14 +50,14 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
ApplicationUser applicationUser = _context.Users.Include(u=>u.Roles).Include(u=>u.Logins).Include(u=>u.Claims).Single(m => m.Id == id); ApplicationUser applicationUser = _context.Users.Single(m => m.Id == id);
if (applicationUser == null) if (applicationUser == null)
{ {
return StatusCode(404); return NotFound();
} }
return Ok(applicationUser); return Ok(applicationUser);
@ -68,25 +69,25 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
if (id != applicationUser.Id) if (id != applicationUser.Id)
{ {
return HttpBadRequest(); return BadRequest();
} }
_context.Entry(applicationUser).State = EntityState.Modified; _context.Entry(applicationUser).State = EntityState.Modified;
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateConcurrencyException) catch (DbUpdateConcurrencyException)
{ {
if (!ApplicationUserExists(id)) if (!ApplicationUserExists(id))
{ {
return StatusCode(404); return NotFound();
} }
else else
{ {
@ -94,7 +95,7 @@ namespace Yavsc.Controllers
} }
} }
return new HttpStatusCodeResult(StatusCodes.Status204NoContent); return new StatusCodeResult(StatusCodes.Status204NoContent);
} }
// POST: api/ApplicationUserApi // POST: api/ApplicationUserApi
@ -103,19 +104,19 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
_context.Users.Add(applicationUser); _context.Users.Add(applicationUser);
try try
{ {
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
} }
catch (DbUpdateException) catch (DbUpdateException)
{ {
if (ApplicationUserExists(applicationUser.Id)) if (ApplicationUserExists(applicationUser.Id))
{ {
return new HttpStatusCodeResult(StatusCodes.Status409Conflict); return new StatusCodeResult(StatusCodes.Status409Conflict);
} }
else else
{ {
@ -132,17 +133,17 @@ namespace Yavsc.Controllers
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
{ {
return HttpBadRequest(ModelState); return BadRequest(ModelState);
} }
ApplicationUser applicationUser = _context.Users.Single(m => m.Id == id); ApplicationUser applicationUser = _context.Users.Single(m => m.Id == id);
if (applicationUser == null) if (applicationUser == null)
{ {
return StatusCode(404); return NotFound();
} }
_context.Users.Remove(applicationUser); _context.Users.Remove(applicationUser);
_context.SaveChanges(_userManager.GetUserId(User)); _context.SaveChanges(User.GetUserId());
return Ok(applicationUser); return Ok(applicationUser);
} }

@ -5,6 +5,7 @@ using System.Threading.Tasks;
using System.Linq; using System.Linq;
using Yavsc.Models; using Yavsc.Models;
using Yavsc.Abstract.Identity; using Yavsc.Abstract.Identity;
using Yavsc.Helpers;
namespace Yavsc.ApiControllers.accounting namespace Yavsc.ApiControllers.accounting
{ {
@ -22,9 +23,9 @@ namespace Yavsc.ApiControllers.accounting
[HttpGet("{allow}",Name ="setmonthlyemail")] [HttpGet("{allow}",Name ="setmonthlyemail")]
public async Task<object> SetMonthlyEmail(bool allow) public async Task<object> SetMonthlyEmail(bool allow)
{ {
var user = await _userManager.FindByIdAsync(_userManager.GetUserId(User)); var user = await _userManager.FindByIdAsync(User.GetUserId());
user.AllowMonthlyEmail = allow; user.AllowMonthlyEmail = allow;
_dbContext.SaveChanges(_userManager.GetUserId(User)); _dbContext.SaveChanges(User.GetUserId());
return Ok(new { monthlyEmailPrefSaved = allow }); return Ok(new { monthlyEmailPrefSaved = allow });
} }

@ -1,23 +0,0 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Yavsc.Interfaces;
using Yavsc.ViewModels.Auth;
namespace Yavsc.AuthorizationHandlers
{
public class AnnouceEditHandler : AuthorizationHandler<EditRequirement, IOwned>
{
protected override void Handle(AuthorizationContext context, EditRequirement requirement,
IOwned resource)
{
if (context.User.IsInRole(Constants.BlogModeratorGroupName)
|| context.User.IsInRole(Constants.AdminGroupName))
context.Succeed(requirement);
if (resource.OwnerId == context._userManager.GetUserId(User))
context.Succeed(requirement);
}
}
}

@ -1,21 +0,0 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Yavsc.ViewModels.Auth;
namespace Yavsc.AuthorizationHandlers
{
using Billing;
public class BillEditHandler : AuthorizationHandler<EditRequirement, IBillable>
{
protected override void Handle(AuthorizationContext context, EditRequirement requirement, IBillable resource)
{
if (context.User.IsInRole("FrontOffice"))
context.Succeed(requirement);
else if (context.User.Identity.IsAuthenticated)
if (resource.ClientId == context._userManager.GetUserId(User))
context.Succeed(requirement);
}
}
}

@ -1,23 +0,0 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Yavsc.ViewModels.Auth;
namespace Yavsc.AuthorizationHandlers
{
using Billing;
public class BillViewHandler : AuthorizationHandler<ViewRequirement, IBillable>
{
protected override void Handle(AuthorizationContext context, ViewRequirement requirement, IBillable resource)
{
if (context.User.IsInRole("FrontOffice"))
context.Succeed(requirement);
else if (context.User.Identity.IsAuthenticated)
if (resource.ClientId == context._userManager.GetUserId(User))
context.Succeed(requirement);
else if (resource.PerformerId == context._userManager.GetUserId(User))
context.Succeed(requirement);
}
}
}

@ -1,20 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using Yavsc.Models.Blog;
using Yavsc.ViewModels.Auth;
namespace Yavsc.AuthorizationHandlers
{
public class BlogEditHandler : AuthorizationHandler<EditRequirement, BlogPost>
{
protected override void Handle(AuthorizationContext context, EditRequirement requirement, BlogPost resource)
{
if (context.User.IsInRole(Constants.BlogModeratorGroupName))
context.Succeed(requirement);
else if (context.User.Identity.IsAuthenticated)
if (resource.AuthorId == context._userManager.GetUserId(User))
context.Succeed(requirement);
}
}
}

@ -1,35 +0,0 @@
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Yavsc.Models.Blog;
using Yavsc.ViewModels.Auth;
namespace Yavsc.AuthorizationHandlers
{
public class BlogViewHandler : AuthorizationHandler<ViewRequirement, BlogPost>
{
protected override void Handle(AuthorizationContext context, ViewRequirement requirement, BlogPost resource)
{
bool ok=false;
if (resource.Visible) {
if (resource.ACL==null)
ok=true;
else if (resource.ACL.Count==0) ok=true;
else {
if (context.User.IsSignedIn()) {
var uid = context._userManager.GetUserId(User);
if (resource.ACL.Any(a=>a.Allowed!=null && a.Allowed.Members.Any(m=>m.MemberId == uid )))
ok=true;
}
}
}
if (ok) context.Succeed(requirement);
else {
if (context.User.IsInRole(Constants.AdminGroupName) ||
context.User.IsInRole(Constants.BlogModeratorGroupName))
context.Succeed(requirement);
else context.Fail();
}
}
}
}

@ -1,18 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Yavsc.ViewModels.Auth;
namespace Yavsc.AuthorizationHandlers
{
public class HasBadgeHandler : AuthorizationHandler<PrivateChatEntryRequirement>
{
protected override void Handle(AuthorizationContext context, PrivateChatEntryRequirement requirement)
{
if (!context.User.HasClaim(c => c.Type == "BadgeNumber" &&
c.Issuer == Startup.Authority))
{
return;
}
context.Succeed(requirement);
}
}
}

@ -1,28 +0,0 @@
using System;
using Microsoft.AspNetCore.Authorization;
using Yavsc.ViewModels.Auth;
namespace Yavsc.AuthorizationHandlers
{
public class HasTemporaryPassHandler : AuthorizationHandler<PrivateChatEntryRequirement>
{
protected override void Handle(AuthorizationContext context, PrivateChatEntryRequirement requirement)
{
if (!context.User.HasClaim(c => c.Type == "TemporaryBadgeExpiry" &&
c.Issuer == Startup.Authority))
{
return;
}
var temporaryBadgeExpiry =
Convert.ToDateTime(context.User.FindFirst(
c => c.Type == "TemporaryBadgeExpiry" &&
c.Issuer == Startup.Authority).Value);
if (temporaryBadgeExpiry > DateTime.Now)
{
context.Succeed(requirement);
}
}
}
}

@ -1,18 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Yavsc.Server.Models.IT.SourceCode;
using Yavsc.ViewModels.Auth;
namespace Yavsc.AuthorizationHandlers
{
public class ManageGitHookHandler: AuthorizationHandler<EditRequirement, GitRepositoryReference>
{
protected override void Handle(AuthorizationContext context, EditRequirement requirement, GitRepositoryReference resource)
{
if (context.User.IsInRole("FrontOffice"))
context.Succeed(requirement);
else if (context.User.Identity.IsAuthenticated)
context.Succeed(requirement);
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…