├── .dockerignore ├── .gitattributes ├── .github └── workflows │ └── dotnet.yml ├── .gitignore ├── README.md ├── ReactwithDotnetCore.sln └── ReactwithDotnetCore ├── .config └── dotnet-tools.json ├── Controllers ├── LoginController.cs ├── StudentController.cs └── WeatherForecastController.cs ├── Dockerfile ├── Model └── User.cs ├── Program.cs ├── Properties └── launchSettings.json ├── ReactwithDotnetCore.csproj ├── ReactwithDotnetCore.http ├── WeatherForecast.cs ├── appsettings.Development.json ├── appsettings.json └── db-script.sql /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.classpath 2 | **/.dockerignore 3 | **/.env 4 | **/.git 5 | **/.gitignore 6 | **/.project 7 | **/.settings 8 | **/.toolstarget 9 | **/.vs 10 | **/.vscode 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md 26 | !**/.gitignore 27 | !.git/HEAD 28 | !.git/config 29 | !.git/packed-refs 30 | !.git/refs/heads/** -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a .NET project 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-net 3 | 4 | name: .NET 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | pull_request: 10 | branches: [ "master" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Setup .NET 20 | uses: actions/setup-dotnet@v3 21 | with: 22 | dotnet-version: 6.0.x 23 | - name: Restore dependencies 24 | run: dotnet restore 25 | - name: Build 26 | run: dotnet build --no-restore 27 | - name: Test 28 | run: dotnet test --no-build --verbosity normal 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | React JS Front End Code React JS Front End 2 | -------------------------------------------------------------------------------- /ReactwithDotnetCore.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.8.34330.188 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ReactwithDotnetCore", "ReactwithDotnetCore\ReactwithDotnetCore.csproj", "{B9981DF4-977D-405F-8BFD-EBDE1B897E02}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {B9981DF4-977D-405F-8BFD-EBDE1B897E02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {B9981DF4-977D-405F-8BFD-EBDE1B897E02}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {B9981DF4-977D-405F-8BFD-EBDE1B897E02}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {B9981DF4-977D-405F-8BFD-EBDE1B897E02}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {DEA053E0-5736-456C-AD24-CE51924F3846} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /ReactwithDotnetCore/.config/dotnet-tools.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "isRoot": true, 4 | "tools": { 5 | "dotnet-ef": { 6 | "version": "8.0.1", 7 | "commands": [ 8 | "dotnet-ef" 9 | ] 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /ReactwithDotnetCore/Controllers/LoginController.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Microsoft.AspNetCore.Authorization; 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.Data.SqlClient; 5 | using Microsoft.IdentityModel.Tokens; 6 | using ReactwithDotnetCore.Model; 7 | using System.Data; 8 | using System.IdentityModel.Tokens.Jwt; 9 | using System.Security.Claims; 10 | using System.Security.Cryptography; 11 | using System.Text; 12 | 13 | namespace ReactwithDotnetCore.Controllers 14 | { 15 | public class LoginController(IConfiguration configuration) : Controller 16 | { 17 | private readonly string _connectionString = configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string is missing."); 18 | 19 | [AllowAnonymous] 20 | [HttpPost("userlogin")] 21 | public async Task UserLogin([FromBody] User login) 22 | { 23 | IActionResult response = Unauthorized(); 24 | var user = await AuthenticateUser(login); 25 | if (user != null) 26 | { 27 | var (tokenString, refreshToken) = GenerateTokens(user); 28 | response = Ok(new { message = "success", token = tokenString, refreshToken }); 29 | } 30 | return response; 31 | } 32 | 33 | [AllowAnonymous] 34 | [HttpPost("userregister")] 35 | public async Task UserRegister([FromBody] User register) 36 | { 37 | try 38 | { 39 | using IDbConnection dbConnection = new SqlConnection(_connectionString); 40 | dbConnection.Open(); 41 | 42 | string query = "INSERT INTO TBLB_User (username, emailaddress, password,dateofjoin) VALUES (@UserName, @EmailAddress, @Password , GETDATE())"; 43 | int rowsAffected = await dbConnection.ExecuteAsync(query, register); 44 | 45 | if (rowsAffected > 0) 46 | { 47 | return Ok(register); 48 | } 49 | else 50 | { 51 | return BadRequest("Failed to insert the student record."); 52 | } 53 | } 54 | catch (Exception ex) 55 | { 56 | return StatusCode(500, $"Internal Server Error: {ex.Message}"); 57 | } 58 | } 59 | 60 | /// 61 | /* 62 | * 63 | The purpose of a refresh token is to provide a way to obtain a new access token without requiring the 64 | user to re-enter their credentials.Access tokens have a limited lifespan, and when they expire, the 65 | user would typically need to log in again to get a new access token. 66 | 67 | With a refresh token mechanism, when the access token expires, the client can use the refresh token 68 | to obtain a new access token without requiring the user's credentials. This helps in maintaining a 69 | balance between security and user convenience. The refresh token is a long-lived token that can 70 | be securely stored by the client and used to request new access tokens as needed. 71 | * 72 | */ 73 | /// 74 | /// 75 | /// 76 | [AllowAnonymous] 77 | [HttpPost("refreshtoken")] 78 | public IActionResult RefreshToken([FromBody] RefreshTokenRequest refreshTokenRequest) 79 | { 80 | IActionResult response = BadRequest("Invalid token"); 81 | var principal = GetPrincipalFromExpiredToken(refreshTokenRequest.Token); 82 | 83 | if (principal != null) 84 | { 85 | var username = principal?.Claims?.FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value; 86 | if (username != null) 87 | { 88 | var user = GetUserByUsername(username); 89 | 90 | if (user != null && refreshTokenRequest.RefreshToken == user.RefreshToken) 91 | { 92 | var (tokenString, newRefreshToken) = GenerateTokens(user); 93 | response = Ok(new { token = tokenString, refreshToken = newRefreshToken }); 94 | } 95 | } 96 | } 97 | 98 | return response; 99 | } 100 | 101 | private (string tokenString, string refreshToken) GenerateTokens(User userInfo) 102 | { 103 | var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]?.PadRight(32) ?? string.Empty)); 104 | var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); 105 | 106 | var claims = new[] { 107 | new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username), 108 | new Claim(JwtRegisteredClaimNames.Email, userInfo.EmailAddress), 109 | new Claim("DateOfJoin", userInfo.DateOfJoin.ToString("yyyy-MM-dd")), 110 | new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) 111 | }; 112 | 113 | var token = new JwtSecurityToken(configuration?["Jwt:Issuer"], 114 | configuration?["Jwt:Audience"], 115 | claims, 116 | expires: DateTime.Now.AddMinutes(120), 117 | signingCredentials: credentials); 118 | 119 | var refreshToken = GenerateRefreshToken(); 120 | userInfo.RefreshToken = refreshToken; // Save refresh token to user in your data store 121 | 122 | // Update the refresh token in the database 123 | UpdateRefreshTokenInDatabase(userInfo.Username, refreshToken); 124 | 125 | return (new JwtSecurityTokenHandler().WriteToken(token), refreshToken); 126 | } 127 | 128 | private static string GenerateRefreshToken() 129 | { 130 | // Generate a random refresh token (you may use a more sophisticated method) 131 | var randomNumber = new byte[32]; 132 | using var rng = RandomNumberGenerator.Create(); 133 | rng.GetBytes(randomNumber); 134 | return Convert.ToBase64String(randomNumber); 135 | } 136 | 137 | private ClaimsPrincipal GetPrincipalFromExpiredToken(string token) 138 | { 139 | var tokenValidationParameters = new TokenValidationParameters 140 | { 141 | ValidateIssuer = true, 142 | ValidateAudience = true, 143 | ValidateLifetime = false, // This will allow an expired token to be parsed 144 | ValidateIssuerSigningKey = true, 145 | ValidIssuer = configuration["Jwt:Issuer"], 146 | ValidAudience = configuration["Jwt:Audience"], 147 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"] ?? string.Empty)) 148 | }; 149 | 150 | var tokenHandler = new JwtSecurityTokenHandler(); 151 | 152 | // The following line will throw an exception if the token is expired 153 | var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken); 154 | 155 | return principal; 156 | } 157 | 158 | private async Task AuthenticateUser(User login) 159 | { 160 | using IDbConnection dbConnection = new SqlConnection(_connectionString); 161 | dbConnection.Open(); 162 | 163 | string query = "SELECT * FROM TBLB_User WITH(NOLOCK) WHERE Username = @Username AND Password = @Password"; 164 | var users = await dbConnection.QueryAsync(query, new { login.Username, login.Password }); 165 | 166 | return users.FirstOrDefault() ?? new User(); 167 | } 168 | 169 | private User GetUserByUsername(string username) 170 | { 171 | using IDbConnection dbConnection = new SqlConnection(_connectionString); 172 | dbConnection.Open(); 173 | 174 | string query = "SELECT * FROM TBLB_User WITH(NOLOCK) WHERE Username = @Username"; 175 | var user = dbConnection.Query(query, new { Username = username }).FirstOrDefault(); 176 | 177 | return user ?? new User(); 178 | } 179 | 180 | private void UpdateRefreshTokenInDatabase(string username, string newRefreshToken) 181 | { 182 | using IDbConnection dbConnection = new SqlConnection(_connectionString); 183 | dbConnection.Open(); 184 | 185 | string updateQuery = "UPDATE TBLB_User SET RefreshToken = @RefreshToken WHERE Username = @Username"; 186 | dbConnection.Execute(updateQuery, new { RefreshToken = newRefreshToken, Username = username }); 187 | } 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /ReactwithDotnetCore/Controllers/StudentController.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Microsoft.AspNetCore.Authorization; 3 | using Microsoft.AspNetCore.Mvc; 4 | using Microsoft.Data.SqlClient; 5 | using System.Data; 6 | 7 | namespace ReactwithDotnetCore.Controllers 8 | { 9 | [ApiController] 10 | [Route("[controller]")] 11 | [Authorize] 12 | 13 | public class StudentController(IConfiguration configuration) : ControllerBase 14 | { 15 | private readonly string? _connectionString = configuration.GetConnectionString("DefaultConnection"); 16 | private readonly string? _connectionString2 = configuration.GetConnectionString("DefaultConnection2"); 17 | 18 | /// 19 | /// Student Data Process API 20 | /// 21 | public class Student 22 | { 23 | public int? rollNumber { get; set; } 24 | public string? name { get; set; } 25 | public string? email { get; set; } 26 | public string? phone { get; set; } 27 | public string? image { get; set; } = "default.png"; 28 | } 29 | 30 | [Authorize] 31 | [HttpGet("getallstudents")] 32 | public async Task GetAllStudents() 33 | { 34 | try 35 | { 36 | /* 37 | 38 | //This code assumes that the token is in the "Bearer " format in the Authorization header. 39 | //It splits the header and takes the last part as the token for validation. If your token format is 40 | //different, adjust the code accordingly. 41 | 42 | // Retrieve the user name from the claims 43 | var userName = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; 44 | 45 | // Retrieve the token from the Authorization header 46 | var token = HttpContext.Request.Headers.Authorization.FirstOrDefault()?.Split(" ").Last(); 47 | 48 | if (string.IsNullOrEmpty(token)) 49 | { 50 | return Unauthorized("Token not provided"); 51 | } 52 | 53 | // Validate the token 54 | var tokenHandler = new JwtSecurityTokenHandler(); 55 | var validationParameters = new TokenValidationParameters 56 | { 57 | ValidateIssuer = true, 58 | ValidateAudience = true, 59 | ValidateLifetime = true, 60 | ValidateIssuerSigningKey = true, 61 | ValidIssuer = configuration?["Jwt:Issuer"]?.ToString(), 62 | ValidAudience = configuration?["Jwt:Audience"]?.ToString(), 63 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration?["Jwt:Key"]?.PadRight(32))) 64 | }; 65 | 66 | var principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken); 67 | 68 | // At this point, the token is valid, and you can retrieve additional claims 69 | var dateOfJoin = principal.FindFirst("DateOfJoin")?.Value; 70 | 71 | */ 72 | 73 | var students = await GetStudents(); 74 | 75 | return Ok(students); 76 | } 77 | catch (Exception ex) 78 | { 79 | return StatusCode(500, $"Internal Server Error: {ex.Message}"); 80 | } 81 | } 82 | 83 | [HttpPost("insertorupdatestudent")] 84 | public async Task InsertOrUpdateStudent(Student student) 85 | { 86 | try 87 | { 88 | using IDbConnection dbConnection = new SqlConnection(_connectionString); 89 | dbConnection.Open(); 90 | 91 | if (student.rollNumber.HasValue && student.rollNumber > 0) 92 | { 93 | // Update record if rollNumber is greater than 0 94 | string updateQuery = "UPDATE TBLB_Student SET name = @Name, email = @Email, phone = @Phone, image = @Image WHERE rollNumber = @rollNumber;"; 95 | int rowsAffected = await dbConnection.ExecuteAsync(updateQuery, student); 96 | 97 | if (rowsAffected > 0) 98 | { 99 | return await GetStudents(); 100 | } 101 | else 102 | { 103 | return BadRequest("Failed to update the student record."); 104 | } 105 | } 106 | else 107 | { 108 | // Insert record if rollNumber is not provided or less than or equal to 0 109 | string insertQuery = "INSERT INTO TBLB_Student (name, email, phone, image) VALUES (@Name, @Email, @Phone, @Image);"; 110 | int rowsAffected = await dbConnection.ExecuteAsync(insertQuery, student); 111 | 112 | if (rowsAffected > 0) 113 | { 114 | return await GetStudents(); 115 | } 116 | else 117 | { 118 | return BadRequest("Failed to insert the student record."); 119 | } 120 | } 121 | } 122 | catch (Exception ex) 123 | { 124 | return StatusCode(500, $"Internal Server Error: {ex.Message}"); 125 | } 126 | } 127 | 128 | private async Task GetStudents() 129 | { 130 | try 131 | { 132 | using IDbConnection dbConnection = new SqlConnection(_connectionString); 133 | dbConnection.Open(); 134 | string query = "SELECT * FROM TBLB_Student WITH(NOLOCK);"; 135 | var students = await dbConnection.QueryAsync(query); 136 | return Ok(students); 137 | } 138 | catch (Exception ex) 139 | { 140 | ex.ToString(); 141 | throw; 142 | } 143 | } 144 | 145 | [HttpPost("deletestudent/{rollNumber}")] 146 | public async Task DeleteStudent(int rollNumber) 147 | { 148 | try 149 | { 150 | using IDbConnection dbConnection = new SqlConnection(_connectionString); 151 | dbConnection.Open(); 152 | 153 | string query = "DELETE FROM TBLB_Student WHERE rollNumber = @rollNumber"; 154 | int rowsAffected = await dbConnection.ExecuteAsync(query, new { RollNumber = rollNumber }); 155 | 156 | if (rowsAffected > 0) 157 | { 158 | return Ok($"Student with Roll Number {rollNumber} deleted successfully."); 159 | } 160 | else 161 | { 162 | return NotFound($"Student with Roll Number {rollNumber} not found."); 163 | } 164 | } 165 | catch (Exception ex) 166 | { 167 | return StatusCode(500, $"Internal Server Error: {ex.Message}"); 168 | } 169 | } 170 | 171 | /// 172 | /// Sale Data TEST API 173 | /// 174 | 175 | [HttpGet("storenodata")] 176 | public async Task GetStoreNo() 177 | { 178 | using var connection = new SqlConnection(_connectionString2); 179 | connection.Open(); 180 | var sales = await connection.QueryAsync(@"SELECT DISTINCT 181 | StoreID 182 | FROM TBLT_Sale WITH(NOLOCK) 183 | ORDER BY StoreID DESC; 184 | "); 185 | return Ok(sales); 186 | } 187 | 188 | [HttpGet("salesdata")] 189 | public async Task GetSales() 190 | { 191 | using var connection = new SqlConnection(_connectionString2); 192 | connection.Open(); 193 | var sales = await connection.QueryAsync(@"SELECT SaleID 194 | ,UniqueSessionId 195 | ,StoreID 196 | ,SaleQty 197 | ,SaleTotal 198 | ,SaleUserName 199 | FROM TBLT_Sale WITH(NOLOCK) 200 | ORDER BY SaleID DESC; 201 | "); 202 | return Ok(sales); 203 | } 204 | 205 | [HttpGet("saleslogdata")] 206 | public async Task GetSalesLogs() 207 | { 208 | using var connection = new SqlConnection(_connectionString2); 209 | connection.Open(); 210 | var saleslogs = await connection.QueryAsync(@"SELECT LogId 211 | ,LogType 212 | ,CSVFileName 213 | ,SendTime 214 | ,ResponseTime 215 | ,Status 216 | FROM TBLB_SalesSendDataLog WITH(NOLOCK) 217 | ORDER BY LogId DESC; 218 | "); 219 | return Ok(saleslogs); 220 | } 221 | 222 | [HttpPost("salesdatapost")] 223 | public IActionResult SendSalesData(List objsales) 224 | { 225 | return Ok(objsales); 226 | } 227 | 228 | [HttpGet("dummy")] 229 | public IActionResult GetDummyData() 230 | { 231 | var dummyData = new List { "Dummy1", "Dummy2", "Dummy3" }; 232 | return Ok(dummyData); 233 | } 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /ReactwithDotnetCore/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | namespace ReactwithDotnetCore.Controllers 5 | { 6 | [ApiController] 7 | [Route("[controller]")] 8 | public class WeatherForecastController : ControllerBase 9 | { 10 | private static readonly string[] Summaries = 11 | [ 12 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 13 | ]; 14 | 15 | private readonly ILogger _logger; 16 | 17 | public WeatherForecastController(ILogger logger) 18 | { 19 | _logger = logger; 20 | } 21 | 22 | [HttpGet(Name = "GetWeatherForecast")] 23 | public IEnumerable Get() 24 | { 25 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 26 | { 27 | Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), 28 | TemperatureC = Random.Shared.Next(-20, 55), 29 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 30 | }) 31 | .ToArray(); 32 | } 33 | 34 | [HttpGet("dummy")] 35 | public IActionResult GetDummyData() 36 | { 37 | // Replace this with your actual logic 38 | var dummyData = new List { "Dummy1", "Dummy2", "Dummy3" }; 39 | return Ok(dummyData); 40 | } 41 | 42 | [Authorize] 43 | [HttpGet("dummy2")] 44 | public IActionResult GetDummyData2() 45 | { 46 | // Replace this with your actual logic 47 | var dummyData = new List { "Dummy1", "Dummy2", "Dummy3", "Dummy4" }; 48 | return Ok(dummyData); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /ReactwithDotnetCore/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base 4 | USER app 5 | WORKDIR /app 6 | EXPOSE 8080 7 | EXPOSE 8081 8 | 9 | FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build 10 | ARG BUILD_CONFIGURATION=Release 11 | WORKDIR /src 12 | COPY ["ReactwithDotnetCore/ReactwithDotnetCore.csproj", "ReactwithDotnetCore/"] 13 | RUN dotnet restore "./ReactwithDotnetCore/./ReactwithDotnetCore.csproj" 14 | COPY . . 15 | WORKDIR "/src/ReactwithDotnetCore" 16 | RUN dotnet build "./ReactwithDotnetCore.csproj" -c $BUILD_CONFIGURATION -o /app/build 17 | 18 | FROM build AS publish 19 | ARG BUILD_CONFIGURATION=Release 20 | RUN dotnet publish "./ReactwithDotnetCore.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false 21 | 22 | FROM base AS final 23 | WORKDIR /app 24 | COPY --from=publish /app/publish . 25 | ENTRYPOINT ["dotnet", "ReactwithDotnetCore.dll"] -------------------------------------------------------------------------------- /ReactwithDotnetCore/Model/User.cs: -------------------------------------------------------------------------------- 1 | namespace ReactwithDotnetCore.Model 2 | { 3 | public class User 4 | { 5 | public string Username { get; set; } = string.Empty; 6 | public string Password { get; set; } = string.Empty; 7 | public string EmailAddress { get; set; } = string.Empty; 8 | public DateTime DateOfJoin { get; set; } = DateTime.Now; 9 | public string RefreshToken { get; set; } = string.Empty; 10 | } 11 | 12 | public class RefreshTokenRequest 13 | { 14 | public string Token { get; set; } = string.Empty; 15 | public string RefreshToken { get; set; } = string.Empty; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /ReactwithDotnetCore/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authentication.JwtBearer; 2 | using Microsoft.AspNetCore.Rewrite; 3 | using Microsoft.IdentityModel.Tokens; 4 | using Microsoft.OpenApi.Models; 5 | using System.Text; 6 | 7 | const string CorsPolicyName = "_APIPolicy"; 8 | 9 | var builder = WebApplication.CreateBuilder(args); 10 | 11 | builder.Services.AddCors(o => o.AddPolicy(name: CorsPolicyName, builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod())); 12 | 13 | builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 14 | .AddJwtBearer(options => 15 | { 16 | options.TokenValidationParameters = new TokenValidationParameters 17 | { 18 | ValidateIssuer = true, 19 | ValidateAudience = true, 20 | ValidateLifetime = false, // This will allow an expired token to be parsed 21 | ValidateIssuerSigningKey = true, 22 | ValidIssuer = builder.Configuration["Jwt:Issuer"], 23 | ValidAudience = builder.Configuration["Jwt:Audience"], 24 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"] ?? string.Empty)) 25 | }; 26 | }); 27 | 28 | builder.Services.AddAuthorization(); 29 | 30 | // Add services to the container. 31 | 32 | builder.Services.AddControllers(); 33 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 34 | builder.Services.AddEndpointsApiExplorer(); 35 | // Add Swagger 36 | builder.Services.AddSwaggerGen(c => 37 | { 38 | c.SwaggerDoc("v1", new OpenApiInfo { Title = ".Net Core API", Version = "v1" }); 39 | 40 | // Add JWT token configuration 41 | c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme 42 | { 43 | Description = "JWT Authorization header using the Bearer scheme", 44 | Type = SecuritySchemeType.Http, 45 | Scheme = "bearer" 46 | }); 47 | 48 | // Add a requirement for the token 49 | c.AddSecurityRequirement(new OpenApiSecurityRequirement 50 | { 51 | { 52 | new OpenApiSecurityScheme 53 | { 54 | Reference = new OpenApiReference 55 | { 56 | Type = ReferenceType.SecurityScheme, 57 | Id = "Bearer" 58 | } 59 | }, 60 | Array.Empty() 61 | } 62 | }); 63 | }); 64 | 65 | var app = builder.Build(); 66 | 67 | // Configure the HTTP request pipeline. 68 | if (app.Environment.IsDevelopment() || app.Environment.IsProduction()) 69 | { 70 | app.UseSwagger(); 71 | app.UseSwaggerUI(); 72 | } 73 | 74 | var option = new RewriteOptions(); 75 | option.AddRedirect("^$", "swagger"); 76 | app.UseRewriter(option); 77 | 78 | app.UseHttpsRedirection(); 79 | 80 | app.UseCors(CorsPolicyName); 81 | 82 | app.UseAuthorization(); 83 | 84 | app.MapControllers(); 85 | 86 | app.Run(); 87 | -------------------------------------------------------------------------------- /ReactwithDotnetCore/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "http": { 4 | "commandName": "Project", 5 | "launchBrowser": true, 6 | "launchUrl": "swagger", 7 | "environmentVariables": { 8 | "ASPNETCORE_ENVIRONMENT": "Development" 9 | }, 10 | "dotnetRunMessages": true, 11 | "applicationUrl": "http://localhost:5152" 12 | }, 13 | "https": { 14 | "commandName": "Project", 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "environmentVariables": { 18 | "ASPNETCORE_ENVIRONMENT": "Development" 19 | }, 20 | "dotnetRunMessages": true, 21 | "applicationUrl": "https://localhost:7051;http://localhost:5152" 22 | }, 23 | "IIS Express": { 24 | "commandName": "IISExpress", 25 | "launchBrowser": true, 26 | "launchUrl": "swagger", 27 | "environmentVariables": { 28 | "ASPNETCORE_ENVIRONMENT": "Development" 29 | } 30 | }, 31 | "Docker": { 32 | "commandName": "Docker", 33 | "launchBrowser": true, 34 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger", 35 | "environmentVariables": { 36 | "ASPNETCORE_HTTPS_PORTS": "8081", 37 | "ASPNETCORE_HTTP_PORTS": "8080" 38 | }, 39 | "publishAllPorts": true, 40 | "useSSL": true 41 | }, 42 | "WSL": { 43 | "commandName": "WSL2", 44 | "launchBrowser": false, 45 | "launchUrl": "https://localhost:7051/swagger", 46 | "environmentVariables": { 47 | "ASPNETCORE_ENVIRONMENT": "Development", 48 | "ASPNETCORE_URLS": "https://localhost:7051;http://localhost:5152" 49 | }, 50 | "distributionName": "" 51 | } 52 | }, 53 | "$schema": "http://json.schemastore.org/launchsettings.json", 54 | "iisSettings": { 55 | "windowsAuthentication": false, 56 | "anonymousAuthentication": true, 57 | "iisExpress": { 58 | "applicationUrl": "http://localhost:2132", 59 | "sslPort": 44346 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /ReactwithDotnetCore/ReactwithDotnetCore.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | false 8 | afd6b829-b422-438b-8b38-745fe06cf5fa 9 | Linux 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /ReactwithDotnetCore/ReactwithDotnetCore.http: -------------------------------------------------------------------------------- 1 | @ReactwithDotnetCore_HostAddress = http://localhost:5152 2 | 3 | GET {{ReactwithDotnetCore_HostAddress}}/weatherforecast/ 4 | Accept: application/json 5 | 6 | ### 7 | -------------------------------------------------------------------------------- /ReactwithDotnetCore/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | namespace ReactwithDotnetCore 2 | { 3 | public class WeatherForecast 4 | { 5 | public DateOnly Date { get; set; } 6 | 7 | public int TemperatureC { get; set; } 8 | 9 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 10 | 11 | public string? Summary { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /ReactwithDotnetCore/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /ReactwithDotnetCore/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "ConnectionStrings": { 9 | "DefaultConnection": "Server=MSPSYS100;Database=TESTDB;User Id=sa;Password=informix@12;TrustServerCertificate=True;", 10 | "DefaultConnection2": "Server=MSPSYS100;Database=Nebula;User Id=sa;Password=informix@12;TrustServerCertificate=True;" 11 | }, 12 | "Jwt": { 13 | "Key": "this is my custom Secret key for authentication", 14 | "Issuer": "www.ajayvishu.in", 15 | "Audience": "developer" 16 | }, 17 | "AllowedHosts": "*" 18 | } 19 | -------------------------------------------------------------------------------- /ReactwithDotnetCore/db-script.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xp3p3x0/react-backend/745dcc0bea3b4292e90ed680d6fd228cd8545c02/ReactwithDotnetCore/db-script.sql --------------------------------------------------------------------------------