示例#1
0
        public override int GetHashCode()
        {
            unchecked {
                int hash = 17;
                hash = hash * 23 + Status.GetHashCode();
                hash = hash * 23 + Amount.GetHashCode();
                hash = hash * 23 + Currency.GetHashCode();
                hash = hash * 23 + Description.GetHashCode();
                hash = hash * 23 + Capture.GetHashCode();
                hash = hash * 23 + Authorized.GetHashCode();
                hash = hash * 23 + Reversed.GetHashCode();
                hash = hash * 23 + Paid.GetHashCode();
                hash = hash * 23 + Transaction.GetHashCode();
                hash = hash * 23 + Card.GetHashCode();
                hash = hash * 23 + Refunded.GetHashCode();
                hash = hash * 23 + Refunds.GetHashCode();
                hash = hash * 23 + FailureCode.GetHashCode();
                hash = hash * 23 + FailureMessage.GetHashCode();
                hash = hash * 23 + Customer.GetHashCode();
                hash = hash * 23 + IP.GetHashCode();
                hash = hash * 23 + Dispute.GetHashCode();
                hash = hash * 23 + ReturnURI.GetHashCode();
                hash = hash * 23 + AuthorizeURI.GetHashCode();

                return(hash);
            }
        }
示例#2
0
        public override Task <IRestResponse> ExecuteTaskAsync(IRestRequest request)
        {
            Task <IRestResponse> authorizeTask = null;

            if (AccessToken == null)
            {
                var authorizationHeader = request.Parameters.FirstOrDefault(x => x.Type == ParameterType.HttpHeader && x.Name == "Authorization");
                if (authorizationHeader != null)
                {
                    AccessToken   = authorizationHeader.Value.ToString().Replace("Bearer ", "");
                    authorizeTask = DoExecuteTaskAsync("authorize", "", AccessToken);
                }
            }
            if (authorizeTask != null)
            {
                return(authorizeTask.ContinueWith <IRestResponse>(authorizeResponse =>
                {
                    if (authorizeResponse.Result.ResponseStatus == ResponseStatus.Completed)
                    {
                        Authorized?.Invoke(this, EventArgs.Empty);
                        var call = DoExecuteTaskAsync(request);
                        call.Wait(request.Timeout - 1);
                        return call.Result;
                    }
                    else
                    {
                        return authorizeResponse.Result;
                    }
                }));
            }
            else
            {
                return(DoExecuteTaskAsync(request));
            }
        }
示例#3
0
        public void Unsubscribe()
        {
            foreach (var a in Authorized.GetInvocationList())
            {
                Authorized -= (Action)a;
            }

            foreach (var a in RoomCreated.GetInvocationList())
            {
                RoomCreated -= (SocketMessage <RoomDTO>)a;
            }

            foreach (var a in NewMessageReceived.GetInvocationList())
            {
                NewMessageReceived -= (SocketMessage <MessageDTO>)a;
            }

            foreach (var a in RoomParticipated.GetInvocationList())
            {
                RoomParticipated -= (SocketMessage <RoomParticipatedDTO>)a;
            }

            foreach (var a in RoomLeft.GetInvocationList())
            {
                RoomLeft -= (SocketMessage <RoomParticipatedDTO>)a;
            }

            foreach (var a in FileStatusChanged.GetInvocationList())
            {
                FileStatusChanged -= (SocketMessage <FileStatusDTO>)a;
            }
        }
        public void Remove(Authorized obj)
        {
            obj.Excluido = true;
            obj.Liberado = false;

            _db.Entry(obj).State = EntityState.Modified;
            _db.SaveChanges();
        }
 BoolValue <AuthResult> onAuthorizationDone(BoolValue <AuthResult> authResult)
 {
     if (authResult)
     {
         Authorized?.Invoke(this, new AuthResultEventArgs(authResult));
     }
     return(authResult);
 }
示例#6
0
        public IActionResult Edit(Authorized authorized)
        {
            if (ModelState.IsValid)
            {
                _authorizedRepository.Update(authorized);
                return(RedirectToAction("Index"));
            }

            return(View(authorized));
        }
示例#7
0
        public IActionResult Create(Authorized authorized)
        {
            if (ModelState.IsValid)
            {
                authorized.UserId = _userManager.GetUserId(HttpContext.User);
                _authorizedRepository.Add(authorized);
                return(RedirectToAction("Index"));
            }

            return(View(authorized));
        }
示例#8
0
        public async Task Invoke(InvokeContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            ServiceContext serviceContext = context.Request.Properties["ServiceContext"] as ServiceContext;

            MethodCallExpression fbody = context.Request.MethodCallExpression;

            if (fbody == null)
            {
                throw new ServiceException("Expression must be a method call.");
            }

            MethodInfo methodInfo = (MethodInfo)context.Request.Properties["MethodInfo"];

            object[] customAttributes = (object[])context.Request.Properties["CustomAttributes"];
            if (customAttributes == null)
            {
                throw new ArgumentNullException("Service Interface method");
            }

            Authorized authorizedAttributes = customAttributes.FirstOrDefault(t => t.GetType() == typeof(Authorized)) as Authorized;

            bool checkAuthorization = false;

            object[]   classAttributes = (object[])context.Request.Properties["CustomClassAttributes"];
            Authorized classAttribute  = classAttributes.FirstOrDefault(t => t.GetType() == typeof(Authorized)) as Authorized;

            if (classAttribute != null)
            {
                checkAuthorization = true;
            }
            if (authorizedAttributes == null)
            {
                checkAuthorization = false;
            }

            if (checkAuthorization && !authorizationService.isAuthorized(authorizedAttributes, serviceContext))
            {
                throw new ServiceException($"Unauthorized access, Method: {context.Request.ServiceInstance.GetType().Name}.{methodInfo.Name}");
            }
            else
            {
                await _next.Invoke(context);
            }
        }
示例#9
0
        private void HandleSocketMessage(object sender, MessageEventArgs e)
        {
            var message = e.Data;

            try
            {
                var baseMessage = JsonConvert.DeserializeObject <BaseMessage>(message);
                if (baseMessage.Type == SocketMessageTypes.SuccessfullyAuthorized)
                {
                    Authorized?.Invoke();
                }
                else if (baseMessage.Type == SocketMessageTypes.RoomCreated)
                {
                    var response = JsonConvert.DeserializeObject <SocketResponseDTO <RoomDTO> >(message);
                    RoomCreated?.Invoke(response);
                }
                else if (baseMessage.Type == SocketMessageTypes.NewMessage)
                {
                    var response = JsonConvert.DeserializeObject <SocketResponseDTO <MessageDTO> >(message);
                    NewMessageReceived?.Invoke(response);
                }
                else if (baseMessage.Type == SocketMessageTypes.RoomParticipated)
                {
                    var response = JsonConvert.DeserializeObject <SocketResponseDTO <RoomParticipatedDTO> >(message);
                    RoomParticipated?.Invoke(response);
                }
                else if (baseMessage.Type == SocketMessageTypes.RoomLeft)
                {
                    var response = JsonConvert.DeserializeObject <SocketResponseDTO <RoomParticipatedDTO> >(message);
                    RoomLeft?.Invoke(response);
                }
                else if (baseMessage.Type == SocketMessageTypes.FileStatusChanged)
                {
                    var response = JsonConvert.DeserializeObject <SocketResponseDTO <FileStatusDTO> >(message);
                    FileStatusChanged?.Invoke(response);
                }
            }
            catch (Exception ex)
            {
                Failed?.Invoke(ex.Message);
            }
        }
示例#10
0
        public IActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(RedirectToPage("/Index"));
            }

            var pictureToEdit = this.Context.Pictures
                                .Include(a => a.Tags)
                                .Where(b => b.Id == id)
                                .FirstOrDefault();

            if (Authorized.IsAuthorizedUser(pictureToEdit.UserName, this.User.Identity.Name))
            {
                return(RedirectToPage("/Index"));
            }

            string tagsInString = "";

            foreach (var tag in pictureToEdit.Tags)
            {
                tagsInString += this.Context.Tags.Find(tag.TagId).TagName + " ";
            }

            tagsInString.Trim();

            var viewModel = new ViewEditPictureModel
            {
                Id     = (int)id,
                Title  = pictureToEdit.Title,
                Tags   = tagsInString,
                UserId = pictureToEdit.UserId,
            };

            ViewBag.ViewModel = viewModel;

            return(View());
        }
        public ActionResult Schedule(ScheduleViewModel viewModel, string command)
        {
            // User needs to be authorized to create learning days.
            Authorized allowedActions = CheckAuthorized(viewModel.UserId);

            if ((!HasAuthorization(allowedActions, Authorized.Create)))
            {
                return(View("Error", new HandleErrorInfo(
                                new Exception("You may create/edit/remove learning days only for yourself."),
                                "Learning Controller",
                                "Schedule - Create learning day.")));
            }
            if (command == "Add")
            {
                try
                {
                    Debug.WriteLine("Adding a new learning day, date: {0}, title: {1}, description: {2}, topicId: {3}",
                                    viewModel.NewDayDate, viewModel.NewDayTitle, viewModel.NewDayDescription, viewModel.NewDayTopicId);
                    Debug.WriteLine("Target user: {0}", viewModel.UserId);
                    Debug.WriteLine("Days in quarter: {0}", dayManager.getDaysInQuarterCount(viewModel.NewDayDate, viewModel.UserId));
                    Topic topic = new Topic();
                    if (viewModel.NewDayDate.Date < DateTime.Today)
                    {
                        ModelState.AddModelError("", "Cannot add a day to past.");
                    }
                    else if (viewModel.NewDayTitle.IsNullOrWhiteSpace())
                    {
                        ModelState.AddModelError("", "Day title cannot be empty.");
                    }
                    else if (viewModel.CreateTopic && viewModel.NewDayTitle.IsNullOrWhiteSpace())
                    {
                        ModelState.AddModelError("", "Topic Title cannot be empty.");
                    }
                    else if (dayManager.getDaysInQuarterCount(viewModel.NewDayDate, viewModel.UserId) >= 3)
                    {
                        ModelState.AddModelError("", "Cannot add a day for, " + viewModel.NewDayDate + " - already have 3 learning days in the Quarter.");
                    }
                    else if (dayManager.isDateTaken(viewModel.NewDayDate, viewModel.UserId))
                    {
                        ModelState.AddModelError("", "Cannot add a day for, " + viewModel.NewDayDate + " - date already has a learning day.");
                    }

                    if (ModelState.IsValid)
                    {
                        if (viewModel.CreateTopic)
                        {
                            topic = topicManager.createTopic(viewModel.NewTopicTitle, viewModel.NewTopicDescription, viewModel.NewDayTopicId);
                        }
                        else
                        {
                            topic = topicManager.getTopicById(viewModel.NewDayTopicId);
                        }
                        dayManager.createLearningDay(viewModel.NewDayDate, viewModel.NewDayTitle, viewModel.NewDayDescription,
                                                     viewModel.UserId, new List <Topic>()
                        {
                            topic
                        });

                        return(RedirectToAction("Schedule"));
                    }
                    else
                    {
                        viewModel = getData(viewModel);
                        return(View(viewModel));
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine("An error occurred while adding a new Learning day. LearningController ");
                    return(View(getData(viewModel)));
                }
            }
            else
            {
                LearningDay day = dayManager.getLearningDayById(int.Parse(viewModel.ViewedDayId));
                if (day == null)
                {
                    return(View(getData(viewModel)));
                }
                if (command == "Delete")
                {
                    if (day.Date.Date <= DateTime.Today.Date)
                    {
                        ModelState.AddModelError("", "Cannot delete a learning day that has started or is already over.");
                    }
                    else
                    {
                        dayManager.deleteLearningDay(day.LearningDayId, User.Identity.GetUserId());
                    }
                }
                else if (command == "Edit")
                {
                    if (day.Date.Date < DateTime.Today.Date)
                    {
                        ModelState.AddModelError("", "Cannot edit a learning day that is already over.");
                    }
                    else
                    {
                        return(EditLearningDay(day.LearningDayId));
                    }
                }
            }

            return(View(getData(viewModel)));
        }
 // Returns true if a given flag for authorized actions contains specific authorized action.
 // (Authorized.View | Authorized.Edit) & Authorized.View == Authorized.View
 private bool HasAuthorization(Authorized actions, Authorized action)
 {
     return((actions & action) == action);
 }
 // Returns true if a user is authorized to perform the specified action.
 private bool IsAuthorizedTo(Authorized action, string userId)
 {
     return((CheckAuthorized(userId) & action) != 0);
 }
示例#14
0
        public async Task RunAsync(string id)
        {
start:
            if (IsConnected)
            {
                return;
            }
            websocket_cts = new CancellationTokenSource();
            var Authenticator = RacetimeAPI.Instance.Authenticator;

            using (ws = new ClientWebSocket())
            {
                IsConnected = true;

                if (await Authenticator.Authorize())
                {
                    SendSystemMessage($"Authorization successful. Hello, {Authenticator.Identity?.Name}");
                    Authorized?.Invoke(this, null);
                }
                else
                {
                    SendSystemMessage(Authenticator.Error, true);
                    AuthenticationFailed?.Invoke(this, new EventArgs());
                    ConnectionError++;
                    goto cleanup;
                }
                //opening the socket
                ws.Options.SetRequestHeader("Authorization", $"Bearer {Authenticator.AccessToken}");
                try
                {
                    await ws.ConnectAsync(new Uri(FullSocketRoot + "ws/o/race/" + id), websocket_cts.Token);
                }
                catch (WebSocketException wex)
                {
                    ConnectionError++;
                    goto cleanup;
                }

                //initial command to sync LiveSplit
                if (ws.State == WebSocketState.Open)
                {
                    ChannelJoined?.Invoke(this, new EventArgs());
                    SendSystemMessage($"Joined Channel '{id}'");
                    try
                    {
                        ArraySegment <byte> bytesToSend = new ArraySegment <byte>(Encoding.UTF8.GetBytes("{ \"action\":\"getrace\" }"));
                        ws.SendAsync(bytesToSend, WebSocketMessageType.Text, true, CancellationToken.None);
                        await ReceiveAndProcess();

                        if (Race.StartedAt != DateTime.MaxValue)
                        {
                            Model.CurrentState.Run.Offset = DateTime.UtcNow - Race.StartedAt;
                        }
                        else
                        {
                            Model.CurrentState.Run.Offset = -Race.StartDelay;
                        }
                    }
                    catch (Exception ex)
                    {
                        SendSystemMessage("Unable to obtain Race information. Try reloading");
                        //Authenticator.AccessToken = null;
                        //Authenticator.RefreshToken = null;

                        goto cleanup;
                    }
                    try
                    {
                        var rf = new StandardComparisonGeneratorsFactory();

                        if (ConnectionError >= 0) //don't load after every reconnect
                        {
                            SendSystemMessage("Loading chat history...");
                            ArraySegment <byte> otherBytesToSend = new ArraySegment <byte>(Encoding.UTF8.GetBytes("{ \"action\":\"gethistory\" }"));
                            ws.SendAsync(otherBytesToSend, WebSocketMessageType.Text, true, CancellationToken.None);
                            await ReceiveAndProcess();
                        }
                    }
                    catch
                    {
                        SendSystemMessage("Unable to load chat history");
                    }
                }

                ConnectionError = -1;

                while (ws.State == WebSocketState.Open && !websocket_cts.IsCancellationRequested)
                {
                    try
                    {
                        await ReceiveAndProcess();
                    }
                    catch (Exception ex)
                    {
                    }
                }


                switch (ws.State)
                {
                case WebSocketState.CloseSent:
                case WebSocketState.CloseReceived:
                case WebSocketState.Closed:
                    ConnectionError = -1;
                    break;

                default:
                case WebSocketState.Aborted:
                    if (!websocket_cts.IsCancellationRequested)
                    {
                        ConnectionError++;
                    }

                    break;
                }
            }

cleanup:
            IsConnected = false;

            if (ConnectionError >= 0)
            {
                SendSystemMessage($"Auto-reconnect in {reconnectDelays[Math.Min(reconnectDelays.Length-1,ConnectionError)]}s...");
                await Task.Delay(reconnectDelays[Math.Min(reconnectDelays.Length - 1, ConnectionError)] * 1000);

                goto start;
            }
            else
            {
                SendSystemMessage("Disconnect");
            }

            websocket_cts.Dispose();

            Disconnected?.Invoke(this, new EventArgs());
        }
示例#15
0
        public bool IsAuthorized(string user)
        {
            Guard.NotEmpty(user, nameof(user));

            return(Authorized.Any(a => a.Equals(user, StringComparison.OrdinalIgnoreCase)));
        }
 protected virtual void OnAuthorized(TwainCloudAuthorizedEventArgs e)
 {
     Authorized?.Invoke(this, e);
 }
示例#17
0
        public override int GetHashCode()
        {
            unchecked {
                int hash = 17;
                if (Status != default(ChargeStatus))
                {
                    hash = hash * 23 + Status.GetHashCode();
                }
                if (Amount != default(long))
                {
                    hash = hash * 23 + Amount.GetHashCode();
                }
                if (Currency != default(string))
                {
                    hash = hash * 23 + Currency.GetHashCode();
                }
                if (Description != default(string))
                {
                    hash = hash * 23 + Description.GetHashCode();
                }
                if (Metadata != default(IDictionary <string, object>))
                {
                    hash = hash * 23 + Metadata.GetHashCode();
                }
                if (Capture != default(bool))
                {
                    hash = hash * 23 + Capture.GetHashCode();
                }
                if (Authorized != default(bool))
                {
                    hash = hash * 23 + Authorized.GetHashCode();
                }
                if (Reversed != default(bool))
                {
                    hash = hash * 23 + Reversed.GetHashCode();
                }
                if (Paid != default(bool))
                {
                    hash = hash * 23 + Paid.GetHashCode();
                }
                if (Transaction != default(string))
                {
                    hash = hash * 23 + Transaction.GetHashCode();
                }
                if (SourceOfFund != default(SourceOfFunds))
                {
                    hash = hash * 23 + SourceOfFund.GetHashCode();
                }
                if (Card != default(Card))
                {
                    hash = hash * 23 + Card.GetHashCode();
                }
                if (Refunded != default(long))
                {
                    hash = hash * 23 + Refunded.GetHashCode();
                }
                if (Refunds != default(ScopedList <Refund>))
                {
                    hash = hash * 23 + Refunds.GetHashCode();
                }
                if (FailureCode != default(string))
                {
                    hash = hash * 23 + FailureCode.GetHashCode();
                }
                if (FailureMessage != default(string))
                {
                    hash = hash * 23 + FailureMessage.GetHashCode();
                }
                if (Customer != default(string))
                {
                    hash = hash * 23 + Customer.GetHashCode();
                }
                if (IP != default(string))
                {
                    hash = hash * 23 + IP.GetHashCode();
                }
                if (Dispute != default(Dispute))
                {
                    hash = hash * 23 + Dispute.GetHashCode();
                }
                if (ReturnURI != default(string))
                {
                    hash = hash * 23 + ReturnURI.GetHashCode();
                }
                if (AuthorizeURI != default(string))
                {
                    hash = hash * 23 + AuthorizeURI.GetHashCode();
                }
                if (Offsite != default(OffsiteTypes))
                {
                    hash = hash * 23 + Offsite.GetHashCode();
                }
                if (InstallmentTerms != default(int))
                {
                    hash = hash * 23 + InstallmentTerms.GetHashCode();
                }

                return(hash);
            }
        }
 public void Update(Authorized obj)
 {
     _db.Entry(obj).State = EntityState.Modified;
     _db.SaveChanges();
 }
示例#19
0
        /// <summary>
        /// Returns true if CoinInfo instances are equal
        /// </summary>
        /// <param name="other">Instance of CoinInfo to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(CoinInfo other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     CoinType == other.CoinType ||
                     CoinType != null &&
                     CoinType.Equals(other.CoinType)
                     ) &&
                 (
                     WalletName == other.WalletName ||
                     WalletName != null &&
                     WalletName.Equals(other.WalletName)
                 ) &&
                 (
                     Name == other.Name ||
                     Name != null &&
                     Name.Equals(other.Name)
                 ) &&
                 (
                     Symbol == other.Symbol ||
                     Symbol != null &&
                     Symbol.Equals(other.Symbol)
                 ) &&
                 (
                     WalletSymbol == other.WalletSymbol ||
                     WalletSymbol != null &&
                     WalletSymbol.Equals(other.WalletSymbol)
                 ) &&
                 (
                     WalletType == other.WalletType ||
                     WalletType != null &&
                     WalletType.Equals(other.WalletType)
                 ) &&
                 (
                     TransactionFee == other.TransactionFee ||
                     TransactionFee != null &&
                     TransactionFee.Equals(other.TransactionFee)
                 ) &&
                 (
                     Precision == other.Precision ||
                     Precision != null &&
                     Precision.Equals(other.Precision)
                 ) &&
                 (
                     BackingCoinType == other.BackingCoinType ||
                     BackingCoinType != null &&
                     BackingCoinType.Equals(other.BackingCoinType)
                 ) &&
                 (
                     SupportsOutputMemos == other.SupportsOutputMemos ||
                     SupportsOutputMemos != null &&
                     SupportsOutputMemos.Equals(other.SupportsOutputMemos)
                 ) &&
                 (
                     Restricted == other.Restricted ||
                     Restricted != null &&
                     Restricted.Equals(other.Restricted)
                 ) &&
                 (
                     Authorized == other.Authorized ||
                     Authorized != null &&
                     Authorized.Equals(other.Authorized)
                 ) &&
                 (
                     NotAuthorizedReasons == other.NotAuthorizedReasons ||
                     NotAuthorizedReasons != null &&
                     NotAuthorizedReasons.SequenceEqual(other.NotAuthorizedReasons)
                 ));
        }
示例#20
0
        public IActionResult Confirm()
        {
            var pictureToEdit = this.Context.Pictures.Include(a => a.Tags).Where(b => b.Id == this.Id).FirstOrDefault();

            if (Authorized.IsAuthorizedUser(pictureToEdit.UserName, this.User.Identity.Name))
            {
                return(RedirectToPage("/Index"));
            }

            pictureToEdit.Title = this.Title;

            var keywords = this.Tags
                           .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                           .ToList();

            var listOfTagsAll = this.Context.Tags;

            var listOfPictureTags = new List <PictureTag>();

            foreach (var tag in keywords)
            {
                int?tagId = 0;

                try
                {
                    tagId = this.Context.Tags.Where(a => a.TagName == tag).FirstOrDefault().Id;
                }
                catch { }

                if (pictureToEdit.Tags.Any(a => a.Tag.Id == tagId))
                {
                    continue;
                }

                var existsTag = listOfTagsAll.Where(a => a.TagName == tag).FirstOrDefault();

                if (existsTag == null)
                {
                    var newTag = new Tag
                    {
                        TagName = tag
                    };

                    var pictureTag = new PictureTag
                    {
                        Picture   = pictureToEdit,
                        PictureId = pictureToEdit.Id,
                        Tag       = newTag,
                        TagId     = newTag.Id
                    };

                    listOfPictureTags.Add(pictureTag);

                    this.Context.PictureTag.Add(pictureTag);
                    this.Context.Tags.Add(newTag);
                }
                else
                {
                    var pictureTag = new PictureTag
                    {
                        Picture   = pictureToEdit,
                        PictureId = pictureToEdit.Id,
                        Tag       = existsTag,
                        TagId     = existsTag.Id
                    };

                    listOfPictureTags.Add(pictureTag);

                    this.Context.PictureTag.Add(pictureTag);
                }
            }

            pictureToEdit.Tags = listOfPictureTags;

            this.Context.Pictures.Update(pictureToEdit);
            this.Context.SaveChanges();

            return(Redirect($"/viewImage/image/{pictureToEdit.Id}"));
        }
        public async Task <Guid> RetrieveAccessTokenAsync(OperationContext context, Guid flowId)
        {
            var session = context.OpenSystemSession();
            var flow    = session.GetEntity <IOAuthClientFlow>(flowId);

            Util.Check(flow != null, "OAuth client flow not found, ID: {0}", flowId);
            ThrowIfExpired(flow);
            string err = null;

            switch (flow.Status)
            {
            case OAuthFlowStatus.Started: err = "Access not authorized yet."; break;

            case OAuthFlowStatus.TokenRetrieved: err = "Authorization code already used to retrieve token."; break;

            case OAuthFlowStatus.Error: err = "Authorization failed or denied - " + flow.Error; break;
            }
            Util.Check(err == null, "Cannot retrieve token: {0}.", err);
            Util.CheckNotEmpty(flow.AuthorizationCode, "Authorization code not retrieved, cannot retrieve access token.");

            var apiClient     = new WebApiClient(context, flow.Account.Server.TokenRequestUrl, ClientOptions.Default, badRequestContentType: typeof(string));
            var clientSecret  = flow.Account.ClientSecret;
            var server        = flow.Account.Server;
            var serverOptions = server.Options;
            // Some servers expect clientId/secret in Authorization header
            string query;

            if (serverOptions.IsSet(OAuthServerOptions.ClientInfoInAuthHeader))
            {
                AddClientInfoHeader(apiClient, flow.Account.ClientIdentifier, clientSecret);
                query = StringHelper.FormatUri(AccessTokenUrlQueryTemplate, flow.AuthorizationCode, flow.RedirectUrl);
            }
            else
            {
                //others - clientId/secret mixed with other parameters
                query = StringHelper.FormatUri(AccessTokenUrlQueryTemplateWithClientInfo, flow.AuthorizationCode,
                                               flow.RedirectUrl, flow.Account.ClientIdentifier, clientSecret);
            }

            query = StringHelper.FormatUri(AccessTokenUrlQueryTemplateWithClientInfo, flow.AuthorizationCode,
                                           flow.RedirectUrl, flow.Account.ClientIdentifier, clientSecret);


            //Make a call; standard is POST, but some servers use GET (LinkedIn)
            AccessTokenResponse tokenResp;

            if (serverOptions.IsSet(OAuthServerOptions.TokenUseGet))
            {
                //GET, no body
                tokenResp = await apiClient.GetAsync <AccessTokenResponse>("?" + query);
            }
            else
            {
                var formContent = CreateFormUrlEncodedContent(query);
                tokenResp = await apiClient.PostAsync <HttpContent, AccessTokenResponse>(formContent, string.Empty);
            }
            flow.Status = OAuthFlowStatus.TokenRetrieved;
            //LinkedIn returns milliseconds here - it's a bug, reported. So here is workaround
            var expIn = tokenResp.ExpiresIn;

            if (expIn > 1e+9) //if more than one billion, it is milliseconds
            {
                expIn = expIn / 1000;
            }
            var            expires = this.App.TimeService.UtcNow.AddSeconds(expIn);
            OAuthTokenType tokenType;
            var            ok = Enum.TryParse <OAuthTokenType>(tokenResp.TokenType, true, out tokenType); //should be Bearer
            // Create AccessToken entity
            var accessToken = flow.Account.NewOAuthAccessToken(flow.UserId, tokenResp.AccessToken, tokenType,
                                                               tokenResp.RefreshToken, tokenResp.IdToken, flow.Scopes, App.TimeService.UtcNow, expires, Settings.EncryptionChannel);

            // Unpack OpenId id_token - it is JWT token
            if (serverOptions.IsSet(OAuthServerOptions.OpenIdConnect) && !string.IsNullOrWhiteSpace(tokenResp.IdToken))
            {
                var payload = OpenIdConnectUtil.GetJwtPayload(tokenResp.IdToken);
                var idTkn   = Settings.JsonDeserializer.Deserialize <OpenIdToken>(payload);
                accessToken.NewOpenIdToken(idTkn, payload);
            }
            session.SaveChanges();
            Authorized?.Invoke(this, new OAuthClient.OAuthEventArgs(context, flow.Id));
            return(accessToken.Id);
        }
 public void Add(Authorized obj)
 {
     _db.Set <Authorized>().Add(obj);
     _db.SaveChanges();
 }
示例#23
0
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (CoinType != null)
         {
             hashCode = hashCode * 59 + CoinType.GetHashCode();
         }
         if (WalletName != null)
         {
             hashCode = hashCode * 59 + WalletName.GetHashCode();
         }
         if (Name != null)
         {
             hashCode = hashCode * 59 + Name.GetHashCode();
         }
         if (Symbol != null)
         {
             hashCode = hashCode * 59 + Symbol.GetHashCode();
         }
         if (WalletSymbol != null)
         {
             hashCode = hashCode * 59 + WalletSymbol.GetHashCode();
         }
         if (WalletType != null)
         {
             hashCode = hashCode * 59 + WalletType.GetHashCode();
         }
         if (TransactionFee != null)
         {
             hashCode = hashCode * 59 + TransactionFee.GetHashCode();
         }
         if (Precision != null)
         {
             hashCode = hashCode * 59 + Precision.GetHashCode();
         }
         if (BackingCoinType != null)
         {
             hashCode = hashCode * 59 + BackingCoinType.GetHashCode();
         }
         if (SupportsOutputMemos != null)
         {
             hashCode = hashCode * 59 + SupportsOutputMemos.GetHashCode();
         }
         if (Restricted != null)
         {
             hashCode = hashCode * 59 + Restricted.GetHashCode();
         }
         if (Authorized != null)
         {
             hashCode = hashCode * 59 + Authorized.GetHashCode();
         }
         if (NotAuthorizedReasons != null)
         {
             hashCode = hashCode * 59 + NotAuthorizedReasons.GetHashCode();
         }
         return(hashCode);
     }
 }