Exemple #1
0
        protected override void OnOpen()
        {
            using var db = Program.Services.GetRequiredService <ChessDbContext>();
            try
            {
                if (!Handler.findToken(Context.CookieCollection[AuthToken.SessionToken].Value, out var bUser, out _))
                {
                    Context.WebSocket.Close(CloseStatusCode.Normal, "Authentication failed.");
                    return;
                }
                Player = db.Players.FirstOrDefault(x => x.DiscordAccount == ChessService.cast(bUser.Id));
            } catch
            {
                Context.WebSocket.Close(CloseStatusCode.Normal, "Forbidden - must authenticate.");
                return;
            }
            var id = Guid.Parse(Context.QueryString.Get("id"));

            if (ChessService.TimedGames.TryGetValue(id, out var g))
            {
                Game = g;
                Game.ListeningWS.Add(this);
            }
            if (Game.White.Id == Player.Id)
            {
                Changeable = PlayerSide.White;
            }
            else if (Game.Black.Id == Player.Id)
            {
                Changeable = PlayerSide.Black;
            }
            SendStatus(((DateTimeOffset)DateTime.UtcNow).ToUnixTimeSeconds(), true);
        }
        public override PreconditionResult Check(APIContext context)
        {
            if (context.User == null)
            {
                throw new RedirectException("/login", "You must be logged in");
            }
            using var db = Program.Services.GetRequiredService <ChessDbContext>();
            var player = db.Players.FirstOrDefault(x => x.DiscordAccount == ChessService.cast(context.User.Id));

            if (player == null)
            {
                return(PreconditionResult.FromError("Either no connected account, or not found"));
            }
            string newline = context.WantsHTML ? "<br/>" : "\n";

            if (DirectCompare)
            {
                return(player.Permission == _perm?PreconditionResult.FromSuccess() : PreconditionResult.FromError($"Permission failure." + newline +
                                                                                                                  $"You have: {player.Permission}" + newline +
                                                                                                                  $"Requires exactly: {_perm}"));
            }
            return(player.Permission.HasFlag(_perm) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError($"Permission failure." + newline +
                                                                                                                      $"You have: {player.Permission}" + newline +
                                                                                                                      $"Requires: {_perm}"));
        }
 public ChessBase(APIContext c, string path) : base(c, path)
 {
     DB = Program.Services.GetRequiredService <ChessDbContext>();
     if (c.User != null)
     {
         SelfPlayer = DB.Players.FirstOrDefault(x => x.DiscordAccount == ChessService.cast(c.User.Id));
     }
 }
Exemple #4
0
        public static string getUrl(ulong id, Action <MSScopeOptions> action = null)
        {
            var msScope = new MSScopeOptions();

            if (action == null)
            {
                action = x =>
                {
                    x.OpenId    = true;
                    x.User_Read = true;
                }
            }
            ;
            action(msScope);
            string stateValue = id.ToString();

            stateValue += "." + Program.ToBase64(msScope.ToString());
            var ru  = new RequestUrl($"https://login.microsoftonline.com/{Program.Configuration["ms_auth:tenant_id"]}/oauth2/v2.0/authorize");
            var url = ru.CreateAuthorizeUrl(
                clientId: Program.Configuration["ms_auth:client_id"],
                responseType: "id_token code",
                responseMode: "form_post",
                redirectUri: Handler.LocalAPIUrl + "/login/msoauth",
                nonce: DateTime.Now.DayOfYear.ToString(),
                state: stateValue,
                scope: msScope.GetScopes());

            Console.WriteLine(url);
            return(url);
        }

        bool actOnUserProfile(TokenResponse response, HttpClient client)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");

            request.Headers.Add("Authorization", "Bearer " + response.AccessToken);
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var identityResponse = client.SendAsync(request).Result;

            if (!identityResponse.IsSuccessStatusCode)
            {
                RespondRaw("Could not complete Oauth", identityResponse.StatusCode);
                return(false);
            }
            var content = identityResponse.Content.ReadAsStringAsync().Result;
            var jobj    = JObject.Parse(content);

            Context.User.VerifiedEmail = jobj["mail"].ToObject <string>();
            Context.User.IsVerified    = true;
            if (string.IsNullOrWhiteSpace(Context.User.Name) || Context.User.Name == Context.User.Id.ToString())
            {
                Context.User.OverrideName = jobj["displayName"].ToObject <string>();
            }
            var service = Program.Services.GetRequiredService <ChessService>();

            if (service != null && !Context.User.ServiceUser && !Context.User.GeneratedUser)
            {
                using var db = Program.Services.GetRequiredService <ChessDbContext>();
                string name     = $"{jobj["givenName"]} {jobj["surname"].ToObject<string>()[0]}";
                var    existing = db.Players.AsQueryable().FirstOrDefault(x => x.Name == name && !x.IsBuiltInAccount);
                if (existing != null)
                {
                    existing.ConnectedAccount = Context.User.Id;
                }
                else
                {
                    var chs = db.Players.AsQueryable().FirstOrDefault(x => x.DiscordAccount == ChessService.cast(Context.User.Id) && !x.IsBuiltInAccount);
                    if (chs != null)
                    {
                        chs.Name = name;
                    }
                }
                service.OnSave();
            }
            return(true);
        }

        bool actOnTeams(TokenResponse response, HttpClient client)
        {
            var teamsRequest = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/joinedTeams");

            teamsRequest.Headers.Add("Authorization", "Bearer " + response.AccessToken);
            teamsRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var teamsResponse = client.SendAsync(teamsRequest).Result;

            if (!teamsResponse.IsSuccessStatusCode)
            {
                RespondRaw("Could not retrieve your teams information", teamsResponse.StatusCode);
                return(false);
            }
            var content    = teamsResponse.Content.ReadAsStringAsync().Result;
            var jobj       = JObject.Parse(content);
            var jvalue     = jobj["value"];
            var teamsArray = (JArray)jvalue;
            Dictionary <string, string> classes = new Dictionary <string, string>();

            foreach (JToken jTeam in teamsArray)
            {
                var name  = jTeam["displayName"].ToObject <string>();
                var split = name.Split('-');
                if (split.Length != 2)
                {
                    continue;
                }
                // class - Subject
                // eg
                // 1Mt3 - Maths
                classes[split[0].Trim()] = split[1].Trim();
            }
            Context.User.Classes = classes;
            return(true);
        }