예제 #1
0
파일: Ntfy.cs 프로젝트: jimliuxyz/UW
        /// <summary>
        /// 發送訊息到指定tag
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="pns"></param>
        /// <param name="message"></param>
        /// <param name="type">自訂動作</param>
        /// <param name="payload">自訂資料</param>
        private async Task sendToTag(string tag, PNS pns, string message, string type = null, object payload = null)
        {
            var notif  = "";
            var custom = new {
                type    = type,
                payload = payload
            };
            var custom_json = "\"custom\" : " + Newtonsoft.Json.JsonConvert.SerializeObject(custom);

            switch (pns)
            {
            case PNS.apns:
                notif = "{ \"aps\" : {\"alert\":\"" + message + "\"}, " + custom_json + "}";
                await hub.SendAppleNativeNotificationAsync(notif, new string[] { tag });

                break;

            case PNS.gcm:
                notif = "{ \"data\" : {\"message\":\"" + message + "\"}, " + custom_json + "}";
                await hub.SendGcmNativeNotificationAsync(notif, new string[] { tag });

                break;

            default:
                break;
            }
        }
예제 #2
0
        /// <summary>
        /// 向azure notification hub註冊user device的pns與其token
        /// </summary>
        /// <param name="pns"></param>
        /// <param name="pnsToken"></param>
        /// <returns></returns>
        public async Task <IRpcMethodResult> regPnsToken(PNS pns, string pnsToken, User user = null)
        {
            pnsToken = pnsToken.Trim();

            if (user == null)
            {
                var userId = this.accessor.HttpContext.User.FindFirst(c => c.Type == D.CLAIM.USERID).Value;
                user = db.getUserByUserId(userId);
            }

            if (user != null)
            {
                var regId = await this.notifications.updateRegId(user.userId, pns, pnsToken);

                user.ntfInfo            = user.ntfInfo ?? new NtfInfo();
                user.ntfInfo.pns        = pns;
                user.ntfInfo.pnsRegId   = pnsToken;
                user.ntfInfo.azureRegId = regId;

                if (db.upsertUser(user))
                {
                    return(Ok(null));
                }
            }
            return(ERROR_ACT_FAILED);
        }
예제 #3
0
        public async Task UpdateNtfInfo(Pkuid uid, PNS pns, string pnsRegId, string azureRegId)
        {
            var user = await GetById(uid);

            user.ntfInfo = new NtfInfo
            {
                pns        = pns,
                pnsRegId   = pnsRegId,
                azureRegId = azureRegId,
            };
            await Update(user);
        }
예제 #4
0
        /// <summary>
        /// 向azure notification hub註冊user device的pns與其token
        /// </summary>
        /// <param name="pns"></param>
        /// <param name="pnsToken"></param>
        /// <returns></returns>
        public async Task <IRpcMethodResult> regPnsToken(PNS pns, string pnsToken, User user = null)
        {
            pnsToken = pnsToken.Trim();

            var uid = (user != null) ? UserHelper.IdGen.Parse(user.userId) : UserHelper.IdGen.Parse(this.accessor.HttpContext.User.FindFirst(c => c.Type == D.CLAIM.USERID).Value);

            var azureRegId = await this.notifications.updateRegId(uid.Guid, pns, pnsToken);

            var userHelper = new UserHelper();
            await userHelper.UpdateNtfInfo(uid, pns, pnsToken, azureRegId);

            return(Ok());
        }
 public static bool CorrectLength(String str, PNS pns)
 {
     bool IsCorrect = false;
     switch(pns)
     {
         case PNS.Binary: if(str.Length <= 7) IsCorrect = true; break;
         case PNS.Fourfould: if (str.Length <= 3) IsCorrect = true; break;
         case PNS.Octal: if (str.Length <= 2) IsCorrect = true; break;
         case PNS.Decimal: if (str.Length <= 2) IsCorrect = true; break;
         case PNS.Hexadecimal: if (str.Length <= 1) IsCorrect = true; break;
     }
     return IsCorrect;
 }
        public static bool CorrectKey(KeyEventArgs e, PNS pns)
        {
            bool IsCorrect = false;

                switch(pns)
                {
                    case PNS.Binary: if (e.Key == Key.D0 || e.Key == Key.D1 || e.Key == Key.NumPad0 || e.Key == Key.NumPad1) IsCorrect = true; break;
                    case PNS.Fourfould: if ((e.Key >= Key.D0 && e.Key <= Key.D3) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad3)) IsCorrect = true; break;
                    case PNS.Octal: if ((e.Key >= Key.D0 && e.Key <= Key.D7) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad7)) IsCorrect = true ; break;
                    case PNS.Decimal: if ((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)) IsCorrect = true; break;
                    case PNS.Hexadecimal: if ((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.A || e.Key == Key.B || e.Key == Key.C || e.Key == Key.D || e.Key == Key.E || e.Key == Key.F) IsCorrect = true; break;
                }
            return IsCorrect;
        }
예제 #7
0
파일: Ntfy.cs 프로젝트: jimliuxyz/UW
        /// <summary>
        /// 以userId更新其裝置PNS的資訊
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pns"></param>
        /// <param name="pnsToken"></param>
        /// <returns></returns>
        public async Task <string> updateRegId(string userId, PNS pns, string pnsToken)
        {
            string tag = getUserTag(userId);

            //取得或新建azure regId
            string regId = await getRegIdAsync(tag);

            //依pns類型建立註冊描述
            RegistrationDescription registration = null;

            switch (pns)
            {
            case PNS.apns:
                registration = new AppleRegistrationDescription(pnsToken);
                break;

            case PNS.gcm:
                registration = new GcmRegistrationDescription(pnsToken);
                break;

            default:
                break;
            }

            try
            {
                //填入內容並更新到azure notification hub
                registration.RegistrationId = regId;
                registration.Tags           = new HashSet <string>();
                registration.Tags.Add(D.NTFTAG.EVERYBODY);
                registration.Tags.Add(tag);

                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                Console.WriteLine(e.ToString());
                return(null);
            }

            return(registration.RegistrationId);
        }
예제 #8
0
파일: RpcAuth.cs 프로젝트: jimliuxyz/UW
        /// <summary>
        /// 登入API service
        /// </summary>
        /// <param name="phoneno"></param>
        /// <param name="passcode"></param>
        /// <returns></returns>
        public async Task <IRpcMethodResult> login(string phoneno, string passcode, PNS pns, string pnsToken)
        {
            var smsHelper  = new SmsPasscodeHelper();
            var userHelper = new UserHelper();

            try
            {
                // todo : remove this
                Console.WriteLine("萬用passcode未移除!");
                if (passcode == "88888888")
                {
                }
                else
                {
                    // 驗證sms passcode
                    dynamic res = await smsHelper.IsSmsPasscodeMatched(phoneno, passcode);

                    // 驗證失敗
                    if (!res.passed)
                    {
                        return(Bad(res.error));
                    }
                }

                // 取得user
                var user = await userHelper.GetByPhoneno(phoneno);

                var uid = (user != null) ? UserHelper.IdGen.Parse(user.userId) : userHelper.GenUid();

                var tokenRnd = F.NewGuid();
                var jwt      = IssueToken(uid, tokenRnd);
                var jwtHash  = tokenRnd.ToHash(); //todo : each user should have their own signature to verify

                //sign up
                if (user == null)
                {
                    // create new user
                    user = await userHelper.Create(uid, jwtHash, phoneno, phoneno);

                    // reg pns token
                    var nc = (RpcNotification)this.accessor.HttpContext.RequestServices.GetService(typeof(RpcNotification));
                    await nc.regPnsToken(pns, pnsToken, user);

                    // db.addFriends(user.userId, new List<string> { });
                    // db.updateBalance(user.userId, new Dictionary<string, decimal>());
                }
                //sign in
                else
                {
                    // 通知前裝置必須登出
                    var ntfInfo = user.ntfInfo;
                    if (ntfInfo != null && (ntfInfo.pns != pns || ntfInfo.pnsRegId != pnsToken))
                    {
                        await notifications.sendMessage(user.userId, ntfInfo.pns, "someone logged into your account\\nyou've got to logout!(t1)", D.NTFTYPE.LOGOUT);

                        // 避免rpc時間差可能造成regPnsToken在sendMessage之前
                        Task.Delay(3000).Wait();
                    }

                    // 更新裝置pns token
                    if (ntfInfo == null || ntfInfo.pns != pns || ntfInfo.pnsRegId != pnsToken)
                    {
                        var nc = (RpcNotification)this.accessor.HttpContext.RequestServices.GetService(typeof(RpcNotification));
                        await nc.regPnsToken(pns, pnsToken, user);
                    }

                    // update token hash
                    user.jwtHash = jwtHash;
                    await userHelper.Update(user);
                }

                return(Ok(new { token = jwt }));
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            return(ERROR_ACT_FAILED);
        }
 String makeStrRange(PNS pns)
 {
     String strRange = "";
     switch (pns)
     {
         case PNS.Binary: strRange = "Диапазон: 00000000 - 11111111"; break;
         case PNS.Fourfould: strRange = "Диапазон: 0000 - 3333"; break;
         case PNS.Octal: strRange = "Диапазон: 000 - 377"; break;
         case PNS.Decimal: strRange = "Диапазон: 000 - 255"; break;
         case PNS.Hexadecimal: strRange = "Диапазон: 00 - FF"; break;
         default: strRange = "Выберете необходимую систему счисления"; break;
     }
     return strRange;
 }
예제 #10
0
파일: Ntfy.cs 프로젝트: jimliuxyz/UW
        /// <summary>
        /// 對某user發送訊息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pns"></param>
        /// <param name="message"></param>
        /// <param name="type">自訂動作</param>
        /// <param name="payload">自訂資料</param>
        public async Task sendMessage(string userId, PNS pns, string message, string type = null, object payload = null)
        {
            var userTag = getUserTag(userId);

            await sendToTag(userTag, pns, message, type, payload);
        }
 public static void AddMessageTranslate(PNS fromPNS, PNS toPNS)
 {
     String message = "Перевод из " + (int)fromPNS + " ППС в " + (int)toPNS + "ППС" + Environment.NewLine;
     listMessages.Append(message);
 }
예제 #12
0
        /// <summary>
        /// 登入API service
        /// </summary>
        /// <param name="phoneno"></param>
        /// <param name="passcode"></param>
        /// <returns></returns>
        public async Task <IRpcMethodResult> login(string phoneno, string passcode, PNS pns, string pnsToken)
        {
            try
            {
                // 驗證sms passcode
                dynamic res = db.isSmsPasscodeMatched(phoneno, passcode);

                // todo : remove this
                Console.WriteLine("萬用passcode未移除!");
                if (passcode == "88888888")
                {
                }
                else

                // 驗證失敗
                if (!res.passed)
                {
                    return(Bad(res.error));
                }

                // 建立或取得user
                var user = db.getUserByPhone(phoneno);
                if (user != null)
                {
                    // 通知前裝置必須登出
                    var ntfInfo = user.ntfInfo;
                    if (ntfInfo != null && (ntfInfo.pns != pns || ntfInfo.pnsRegId != pnsToken))
                    {
                        await Task.Run(async() =>
                        {
                            await notifications.sendMessage(user.userId, ntfInfo.pns, "someone logged into your account\\nyou've got to logout!(t1)", D.NTFTYPE.LOGOUT);
                            // 避免rpc時間差可能造成regPnsToken在sendMessage之前
                            Task.Delay(3000).Wait();
                        });
                    }

                    // 更新裝置pns token
                    if (ntfInfo == null || ntfInfo.pns != pns || ntfInfo.pnsRegId != pnsToken)
                    {
                        var nc = (RpcNotification)this.accessor.HttpContext.RequestServices.GetService(typeof(RpcNotification));
                        await nc.regPnsToken(pns, pnsToken, user);
                    }
                }
                else
                {
                    //todo : 暫時的假資料供測試
                    user = new User()
                    {
                        userId  = "tempid-" + phoneno, //todo : 暫時以phoneno綁定id 便於識別 (日後移除)
                        phoneno = phoneno,
                        name    = phoneno,
                        // avatar = "https://ionicframework.com/dist/preview-app/www/assets/img/avatar-ts-woody.png",
                        avatar     = "", //empty for default
                        currencies = new List <CurrencySettings> {
                            new CurrencySettings {
                                name      = D.CNY,
                                order     = 0,
                                isDefault = true,
                                isVisible = false
                            },
                            new CurrencySettings {
                                name      = D.USD,
                                order     = 1,
                                isDefault = false,
                                isVisible = false
                            },
                            new CurrencySettings {
                                name      = D.BTC,
                                order     = 2,
                                isDefault = false,
                                isVisible = false
                            },
                            new CurrencySettings {
                                name      = D.ETH,
                                order     = 3,
                                isDefault = false,
                                isVisible = false
                            }
                        }
                    };
                    if (db.upsertUser(user))
                    {
                        user = db.getUserByPhone(phoneno);
                    }

                    var nc = (RpcNotification)this.accessor.HttpContext.RequestServices.GetService(typeof(RpcNotification));
                    await nc.regPnsToken(pns, pnsToken, user);

                    db.addFriends(user.userId, new List <string> {
                    });
                    db.updateBalance(user.userId, new Dictionary <string, decimal>());
                }

                // 發行token (JWT)
                var tokenRnd = F.NewGuid();
                var claims   = new Claim[] {
                    new Claim(ClaimTypes.MobilePhone, phoneno),
                    new Claim(ClaimTypes.Name, user.name),
                    new Claim(ClaimTypes.Role, "User"),
                    new Claim(D.CLAIM.USERID, user.userId),
                    new Claim(D.CLAIM.TOKENRND, tokenRnd)
                };
                var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(R.JWT_SECRET));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                    R.JWT_ISSUER,
                    R.JWT_AUDIENCE,
                    claims,
                    null,         //DateTime.UtcNow, //todo : 日後再決定是否每次token帶入時間加密
                    null,
                    creds);
                var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);

                // update token random
                user.tokenRnd = tokenRnd;
                db.upsertUser(user);

                return(Ok(new { token = tokenStr }));
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            return(ERROR_ACT_FAILED);
        }