How to set generated additional values in pydantic response_model? - fastapi

I the following problem but don't know how to solve it:
How can I add a generated Id in the job.py and set it to the value job_id in JobResponse?
This is my function job.py
from fastapi import FastAPI
from models import JobResponse, JobRequest
app = FastAPI()
#app.post('/job', response_model=JobResponse)
async def create_user(job: JobRequest):
id = return_id_from_database
return job
models.py:
from pydantic import BaseModel
from typing import Optional
class JobRequest(BaseModel):
job_name: Optional[str] = None
class JobResponse(BaseModel):
job_id: Optional[str] = None
job_name: Optional[str] = None

As promised in the comments, my suggestion was useful and thus I'm writing a proper answer for others as well.
The solution was rather simple, as Fastapi expected the function create_user to return an object serializable to JSON and that complies to the definition of the Pydantic model declared as return value.
job.py
from fastapi import FastAPI
from models import JobResponse, JobRequest
app = FastAPI()
#app.post('/job', response_model=JobResponse)
async def create_user(job: JobRequest):
id = return_id_from_database
return new JobResponse(**job.to_dict(), job_id=id)
models.py
from pydantic import BaseModel
from typing import Optional
class JobRequest(BaseModel):
job_name: Optional[str] = None
class JobResponse(JobRequest):
job_id: Optional[str] = None

Related

How to declare user variable of type "firebase.User" with AngularFireAuth?

In my Angular project, I import AngularFireAuth, and then use signInWithEmailAndPassword,
VSCode says the type returned by signInwithEmailAndPassword is firebase.auth.Usercredential. I can't seem to import this type.
Similarly AngularFireAuth.currentUser returns a firebase.User. Not clear how to import that type either. What is the preferred way to store the current user, and how to import the type?
import {AngularFireAuth } from '#angular/fire/compat/auth`
class MyClass {
constructor(private afAuth : AngularFireAuth){}
async login(email : string, pw: string) {
let user = await this.afAuth.signInWithEmailAndPassword(email,pw);
//user is of type firebase.auth.UserCredential
let currentUser = this.afAuth.currentUser;
//currentUser is of type firebase.User;
}
But if I try to either declare the variables types rather than infer them, I can't do it:
async login(email : string, pw: string) {
let user : firebase.auth.UserCredential;
//produces syntax error `..firebase.compat.index has no exported member 'auth'
let user : firebase.User;
//produces syntax error '../firebase.compat.index has no exported member 'User"
}
I've tried to import from various different sources but none seem to work propertly.
How to import the class of object returned either by 'signInWithEmaila/ndPassword()' or
the currentUser property of AngularFireAuth?

Testing usage of Firebase create user functions with Coroutines and calling await() leads to "This job has not completed yet"

I have a simplified test case where I'm calling createUserWithEmailAndPassword(...).await() from FirebaseAuth that leads to the exception
java.lang.IllegalStateException: This job has not completed yet
I'm using the InstantTaskExecutorRule but this doesn't help.
Here is my simplified test class:
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Rule
import org.junit.Test
class FirebaseCoroutineTest {
#get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
val auth = Firebase.auth.apply {
this.useEmulator("10.0.2.2", 9099)
}
#Test
fun testCreateUser() = runBlockingTest {
auth.createUserWithEmailAndPassword("test#user.null", "testpwd").await()
}
}
What's the correct way to do this test.
using runBlocking instead of runBlockingTest solves the issue.

Spring Boot + JWT + Kotlin: login URL 403

Followed this article: https://auth0.com/blog/developing-restful-apis-with-kotlin/
Doing a home grown auth, the second part of the article.
When I try to POST to the login URL, i get a 403 error.
Here is my SignUpController:
package io.bss.api.controller
import io.bss.api.model.User
import io.bss.api.repository.UserRepository
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
#Controller
#RequestMapping("/sign-up")
class SignUpController(val userRepository: UserRepository, val bCryptPasswordEncoder: BCryptPasswordEncoder) {
#PostMapping()
fun signUp(#RequestBody user: User) {
user.password = bCryptPasswordEncoder.encode(user.password)
userRepository.save(user)
}
}
And my web security class:
package io.bss.api.security
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
#Configuration
#EnableWebSecurity
open class WebSecurity(val userDetailsService: UserDetailsService) : WebSecurityConfigurerAdapter() {
#Bean
fun bCryptPasswordEncoder(): BCryptPasswordEncoder {
return BCryptPasswordEncoder()
}
override fun configure(http: HttpSecurity) {
http.csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
.anyRequest().authenticated()
.and()
.addFilter(JWTAuthenticationFilter(authenticationManager()))
.addFilter(JWTAuthorizationFilter(authenticationManager()))
}
override fun configure(auth: AuthenticationManagerBuilder?) {
auth!!.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder())
}
}
I see that the article was written back in June of 2017, so perhaps something in spring boot changed? This is my first time using it, so I wouldn't know.
Problem is you're trying touse #Controller annotation while using REST.
You have 2 options here:
Annotate your class as #RestController
Annotate each method in your controller with #ResponseBody, but you will need to return something then.

Pass data from ASP.NET Webmethod to Angular 2

Hello Stackoverflowers,
Apologies if this is duplicate, I really tried to find a simple answer for this, but I couldn't.
I need to pass some data from ASP.NET Webmethod to my Angular 2 class.
I'm starting off with a very simple string "hello".
How can I use the server side Get() method to populate the value value ?
My .NET server side code:
[WebMethod]
public static string Get()
{
return "Hello Koby";
}
My Angular 2 code (Very simplified):
import {Component} from 'angular2/core';
import {Injectable} from 'angular2/core';
import {HTTP_PROVIDERS, Http, Response, Headers, RequestOptions} from 'angular2/http';
#Component({
selector: 'log',
templateUrl: '/Scripts/Angular2/templates/log.html'
})
export class Log {
private http;
value = ? // <----- This should come from the server
}
Being new to Angular 2, I can accept solutions, workarounds or curse words.
Thanks.

Mock FileInputStream in FileReader can't work using PowerMock

I noticed that in FileReader constructor, the FileInputStream is created. So I what to Mock it in the FileReader class, but it can't work. Can anyone figure it out?
The code it like below:
package util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest({ FileReader.class, ContentReader.class})
public class FileReaderTest {
#Test
public void testGetContent() throws Exception {
File file = PowerMockito.mock(File.class);
InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream("123".getBytes()));
PowerMockito.whenNew(InputStreamReader.class)
.withArguments(Mockito.any(FileInputStream.class)).thenReturn(isr);
Assert.assertEquals("123", ContentReader.getContent(file));
}
}
class ContentReader {
public static String getContent(File file) throws IOException {
String content = "unknown";
BufferedReader in = null;
in = new BufferedReader(new FileReader(file));
content = in.readLine();
in.close();
return content;
}
}
Shot answer - it's impossible, because to mock system classes the PowerMock should be able to modified a client class which uses system class. In your case both classes: who uses and what is used are system classes. More you can read here (it's about static calls of system classes, but same true for mocking constructor call)
Also, please check this good point: don't mock what you don't own. For you it means:
You should wrap reading data from file via util class which you can mock
Write an integration test for your util class. If ContentReader
is an util class then you shouldn't write unit test for it.

Resources