// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <StudentDBContext>(options => { options.UseSqlServer("Data Source=db-mssql;Initial Catalog=s17064;Integrated Security=True"); }); services.AddControllers(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = MyToken.ISSUER, ValidateAudience = true, ValidAudience = MyToken.AUDIENCE, ValidateLifetime = true, IssuerSigningKey = MyToken.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true, }; }); services.AddControllersWithViews(); }
public IActionResult Token(string username, string password) { var identity = GetIdentity(username, password); if (identity == null) { return(BadRequest(new { errorText = "Invalid username or password." })); } var now = DateTime.UtcNow; var jwt = new JwtSecurityToken( issuer: MyToken.ISSUER, audience: MyToken.AUDIENCE, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(MyToken.LIFETIME)), signingCredentials: new SigningCredentials(MyToken.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, username = identity.Name }; return(Json(response)); }
public override MyToken[] Eval(ObjectStream <Char> input, MyDiscardDelegate <char> discarder) { Ensure(input, discarder); // Ignora código descartável inicialmente input.Discard(discarder); if (input.EndOfStream()) { return(null); } var initialPos = input.GetPosition(); char character = input.Next(); if (character != _character) { input.SetPosition(initialPos); return(null); } var token = new MyToken( GetTokenClass(), initialPos, input.GetPosition(), null ); return(new MyToken[] { token }); }
public override MyToken[] Eval(ObjectStream <Char> input, MyDiscardDelegate <char> discarder) { Ensure(input, discarder); // Ignora código descartável inicialmente input.Discard(discarder); if (input.EndOfStream()) { return(null); } var initialPos = input.GetPosition(); var foundTokens = new List <MyToken>(); foreach (var element in _elements) { var elementTokens = element.Eval(input, discarder); // Qualquer elemento do grupo falhando, todo o grupo falha if (elementTokens == null) { return(null); } foundTokens.AddRange(elementTokens); } if (!foundTokens.Any()) { input.SetPosition(initialPos); return(null); } // O próprio elemento de grupo torna-se um token. // Isso é util para ser usado como um demarcador var token = new MyToken( GetTokenClass(), initialPos, input.GetPosition(), null ); var firstToken = new MyToken[] { token }; // Os demais tokens seguem o demarcador return(firstToken.Concat(foundTokens).ToArray()); }
private async System.Threading.Tasks.Task LoginAsync() { if (String.IsNullOrEmpty(UserName) || String.IsNullOrEmpty(Password)) { isIncorrect = true; return; } else if (InternetConnection.Connection) { MyToken myToken = new MyToken(); if (!await myToken.RequestPasswordToken(UserName, Password)) { isIncorrect = true; return; } else { HttpClient client = new HttpClient(); client.SetBearerToken(MyToken.requestPasswordToken.AccessToken); var res = await client.GetAsync("https://localhost:44370/api/UserLicence"); if (_dbContext.Users.Count(t => t.Name == UserName) == 0) { byte[] PasByte = MyHash.GenerateSaltedHash(Encoding.Unicode.GetBytes(Password)); User User = new User(); User.Name = UserName; User.Password = PasByte; _dbContext.Add(User); _dbContext.SaveChanges(); } } } else { User User = new User(); if (_dbContext.Users.Count(t => t.Name == UserName) != 0) { User = _dbContext.Users.Where(t => t.Name == UserName).FirstOrDefault(); } else { isIncorrect = true; return; } } }
private static void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) // Handles _smtpClient.SendCompleted { if (e.Error != null) { Program.Logger.Error($"Send message error: {e.Error.Message}\n\t\t\t target: {e.Error.TargetSite}\n\t\t\t source: {e.Error.Source}\n\t\t\t " + $"innerExeption {(e.Error.InnerException != null ? e.Error.InnerException.Message : "")}"); } else { Program.Logger.Info("Mail sent!"); } MyToken token = (MyToken)e.UserState; try { token.EMessage.Dispose(); } catch (Exception ex) { Program.Logger.Error("Error disposing mail: " + ex.ToString() + " err:" + e.Error.Message); } if (token.EAttachments.Count > 0) { for (int i = 0; i <= token.EAttachments.Count - 1; i++) { if (Directory.Exists(token.EAttachments[i].AttachFullPath)) { try { Directory.Delete(token.EAttachments[i].AttachFullPath, true); } catch (Exception ex) { Program.Logger.Error(ex.ToString() + " err:" + ((e.Error != null) ? e.Error.Message : "")); } } } } // Call Disposable for net >=4 var client = sender as SmtpClient; var disp = (IDisposable)client; disp?.Dispose(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = MyToken.ISSUER, ValidateAudience = true, ValidAudience = MyToken.AUDIENCE, ValidateLifetime = true, IssuerSigningKey = MyToken.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true, }; }); services.AddControllersWithViews(); }
public override MyToken[] Eval(ObjectStream <Char> input, MyDiscardDelegate <char> discarder) { Ensure(input, discarder); // Ignora código descartável inicialmente input.Discard(discarder); var initialPos = input.GetPosition(); var foundChars = new List <Char>(); while (!input.EndOfStream()) { var pos = input.GetPosition(); char c = input.Next(); if (!_validChars.Contains(c)) { input.SetPosition(pos); break; } foundChars.Add(c); } if (!foundChars.Any()) { input.SetPosition(initialPos); return(null); } var token = new MyToken( GetTokenClass(), initialPos, input.GetPosition(), new string(foundChars.ToArray()) ); return(new MyToken[] { token }); }
public async Task <GoogleREspo> Verify([FromBody] MyToken Token) { ReCAPTCHAData _MyData = new ReCAPTCHAData { response = Token.Token, secret = "*****************" }; Debug.WriteLine("Token: " + _MyData.response); Debug.WriteLine("secret key: " + _MyData.secret); HttpClient client = new HttpClient(); string urlStr = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}"; string url = string.Format(urlStr, _MyData.secret, _MyData.response); var response = await client.GetStringAsync(url); //var response = await client.GetStringAsync($"https://www.google.com/recaptcha/api/siteverify?secret={_MyData.secret}&response={_MyData.response}"); var capresp = JsonConvert.DeserializeObject <GoogleREspo>(response); return(capresp); }
public void SendMail() { var smtpClient = new SmtpClient(); var token = new MyToken(); if (_mailList == null) { Program.Logger.Error("List of mail recepients is empty "); return; } try { MailMessage mail = new MailMessage(); ContentType mimeType = new ContentType("text/html"); if (string.IsNullOrEmpty(_mailBody)) { MakeBaseBody(); } var alterBody = "<!DOCTYPE HTML PUBLIC \"-/W3C/DTD HTML 4.0 Transitional/EN\">"; alterBody += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=utf-8\">"; alterBody += "</HEAD><BODY><PRE><DIV>" + _mailBody.Replace(Environment.NewLine, "<br>"); alterBody += "</DIV></PRE></BODY></HTML>"; AlternateView alternate = AlternateView.CreateAlternateViewFromString(alterBody, mimeType); mail.BodyEncoding = Encoding.UTF8; mail.Body = _mailBody; mail.Subject = Subj; mail.SubjectEncoding = Encoding.UTF8; mail.Sender = new MailAddress(Program.Config.SenderEmail); mail.From = new MailAddress($"\"{Program.Config.HotelName}\"<no-reply@{mail.Sender.Host}>"); // SenderEmail)) '"Office-PC" + "<" + SenderEmail + ">") mail.AlternateViews.Add(alternate); foreach (var eAddress in _mailList) { mail.To.Add(eAddress); } if (_attachList.Count > 0) { for (var i = 0; i <= _attachList.Count - 1; i++) { // .Attachments.Add(New Attachment(_attachList.Item(i).AttachFullPath + "\" + _attachList.Item(i).AttachFilename)) mail.Attachments.Add(_attachList[i]); } } //QXqnj019 smtpClient.SendCompleted += smtpClient_SendCompleted; token.EMessage = mail; token.EAttachments = _attachList; smtpClient.Host = Program.Config.SmtpServer; smtpClient.Port = Program.Config.SmtpPort; smtpClient.EnableSsl = Program.Config.EnableSsl; smtpClient.UseDefaultCredentials = true; smtpClient.Credentials = new NetworkCredential(Program.Config.SmtpUser, Program.Config.SmtpPassword); smtpClient.Timeout = 30000; smtpClient.SendAsync(mail, token); } // Try // smtpClient.SendAsync(mail, token) catch (SmtpException ex) { // exept = ex if (_numberOfAttemps > 0) { var innerMsg = ex.InnerException == null ? string.Empty : ex.InnerException.Message; Program.Logger.Error($"{ _numberOfAttemps} Issues of sending mail: {ex.Message} {innerMsg}"); if (ex.StatusCode == SmtpStatusCode.GeneralFailure) { _numberOfAttemps -= 1; SendMail(); } } } }
public override ParsingResultSet Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { MyTokenStream out_token_stream = new MyTokenStream(); MyLexer lexer = new MyLexer(null); MyParser parser = new MyParser(out_token_stream); MyCharStream fake_char_stream = new MyCharStream(); string text = null; lexer.InputStream = fake_char_stream; if (!(reader.TokenType == JsonTokenType.StartObject)) { throw new JsonException(); } reader.Read(); List <string> mode_names = new List <string>(); List <string> channel_names = new List <string>(); List <string> lexer_rule_names = new List <string>(); List <string> literal_names = new List <string>(); List <string> symbolic_names = new List <string>(); Dictionary <string, int> token_type_map = new Dictionary <string, int>(); List <string> parser_rule_names = new List <string>(); Dictionary <int, IParseTree> nodes = new Dictionary <int, IParseTree>(); List <IParseTree> result = new List <IParseTree>(); while (reader.TokenType == JsonTokenType.PropertyName) { string pn = reader.GetString(); reader.Read(); if (pn == "FileName") { var name = reader.GetString(); fake_char_stream.SourceName = name; reader.Read(); } else if (pn == "Text") { out_token_stream.Text = reader.GetString(); fake_char_stream.Text = out_token_stream.Text; text = out_token_stream.Text; reader.Read(); } else if (pn == "Tokens") { if (!(reader.TokenType == JsonTokenType.StartArray)) { throw new JsonException(); } reader.Read(); int token_index = 0; while (reader.TokenType == JsonTokenType.Number) { var type = reader.GetInt32(); reader.Read(); var start = reader.GetInt32(); reader.Read(); var stop = reader.GetInt32(); reader.Read(); var line = reader.GetInt32(); reader.Read(); var column = reader.GetInt32(); reader.Read(); var channel = reader.GetInt32(); reader.Read(); var token = new MyToken(); token.Type = type; token.StartIndex = start; token.StopIndex = stop; token.Line = line; token.Column = column; token.Channel = channel; token.InputStream = lexer.InputStream; token.TokenSource = lexer; token.TokenIndex = token_index++; token.Text = out_token_stream.Text.Substring(token.StartIndex, token.StopIndex - token.StartIndex + 1); out_token_stream.Add(token); } reader.Read(); } else if (pn == "ModeNames") { if (!(reader.TokenType == JsonTokenType.StartArray)) { throw new JsonException(); } reader.Read(); while (reader.TokenType == JsonTokenType.String || reader.TokenType == JsonTokenType.Null) { mode_names.Add(reader.GetString()); reader.Read(); } reader.Read(); lexer._modeNames = mode_names.ToArray(); } else if (pn == "ChannelNames") { if (!(reader.TokenType == JsonTokenType.StartArray)) { throw new JsonException(); } reader.Read(); while (reader.TokenType == JsonTokenType.String) { channel_names.Add(reader.GetString()); reader.Read(); } reader.Read(); lexer._channelNames = channel_names.ToArray(); } else if (pn == "LiteralNames") { if (!(reader.TokenType == JsonTokenType.StartArray)) { throw new JsonException(); } reader.Read(); while (reader.TokenType == JsonTokenType.String || reader.TokenType == JsonTokenType.Null) { literal_names.Add(reader.GetString()); reader.Read(); } reader.Read(); } else if (pn == "SymbolicNames") { if (!(reader.TokenType == JsonTokenType.StartArray)) { throw new JsonException(); } reader.Read(); while (reader.TokenType == JsonTokenType.String || reader.TokenType == JsonTokenType.Null) { symbolic_names.Add(reader.GetString()); reader.Read(); } reader.Read(); } else if (pn == "LexerRuleNames") { if (!(reader.TokenType == JsonTokenType.StartArray)) { throw new JsonException(); } reader.Read(); while (reader.TokenType == JsonTokenType.String || reader.TokenType == JsonTokenType.Null) { lexer_rule_names.Add(reader.GetString()); reader.Read(); } reader.Read(); } else if (pn == "ParserRuleNames") { if (!(reader.TokenType == JsonTokenType.StartArray)) { throw new JsonException(); } reader.Read(); while (reader.TokenType == JsonTokenType.String || reader.TokenType == JsonTokenType.Null) { var name = reader.GetString(); parser_rule_names.Add(name); reader.Read(); } reader.Read(); } else if (pn == "TokenTypeMap") { if (!(reader.TokenType == JsonTokenType.StartArray)) { throw new JsonException(); } reader.Read(); while (reader.TokenType == JsonTokenType.String || reader.TokenType == JsonTokenType.Null) { var name = reader.GetString(); reader.Read(); var tt = reader.GetInt32(); reader.Read(); token_type_map[name] = tt; } reader.Read(); } else if (pn == "Nodes") { List <IParseTree> list_of_nodes = new List <IParseTree>(); if (!(reader.TokenType == JsonTokenType.StartArray)) { throw new JsonException(); } reader.Read(); int current = 1; while (reader.TokenType == JsonTokenType.Number) { int parent = reader.GetInt32(); reader.Read(); int type_of_node = reader.GetInt32(); reader.Read(); var parent_node = parent > 0 ? nodes[parent] as MyParserRuleContext : null; if (type_of_node < 1000000) { MyParserRuleContext foo = new MyParserRuleContext(parent_node, 0) { _ruleIndex = type_of_node }; nodes[current] = foo; if (parent_node == null) { result.Add(foo); } else { parent_node.AddChild((Antlr4.Runtime.RuleContext)foo); } } else { var index = type_of_node - 1000000; var symbol = out_token_stream.Get(index); var foo = new MyTerminalNodeImpl(symbol); nodes[current] = foo; foo.Parent = parent_node; if (parent_node == null) { result.Add(foo); } else { parent_node.AddChild(foo); } } current++; } foreach (var n in result) { Sweep(n); } reader.Read(); } else { throw new JsonException(); } } var vocab = new Vocabulary(literal_names.ToArray(), symbolic_names.ToArray()); parser._vocabulary = vocab; parser._grammarFileName = fake_char_stream.SourceName; parser._ruleNames = parser_rule_names.ToArray(); lexer._vocabulary = vocab; lexer._ruleNames = lexer_rule_names.ToArray(); lexer._tokenTypeMap = token_type_map; var res = new AntlrJson.ParsingResultSet() { FileName = fake_char_stream.SourceName, Stream = out_token_stream, Nodes = result.ToArray(), Lexer = lexer, Parser = parser, Text = text }; return(res); }