投稿時間:2022-02-21 00:19:06 RSSフィード2022-02-21 00:00 分まとめ(22件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… Apple、2022年に少なくとも7種類の新型Macを投入か − まずは3月、そして5〜6月にも発表へ https://taisy0.com/2022/02/20/153550.html apple 2022-02-20 14:30:23
js JavaScriptタグが付けられた新着投稿 - Qiita 【MediaPipe】カメラで手の指を検知するゲームを作ってみた https://qiita.com/tamoco/items/6c8215371e922c48bb20 2022-02-20 23:26:28
Ruby Rubyタグが付けられた新着投稿 - Qiita 【Rails】繰り返し処理におけるインデックスについて https://qiita.com/miya114/items/4447adcbe66759e4d3ea 【Rails】繰り返し処理におけるインデックスについてeachdo文におけるインデックスhogehtmlerblthogeseachwithindexdohogeigtltdivdatacolumnsltigtgtlthogecontentgtltdivgtltendgt上記のように、eachdoをeachwithindexdoと記述し、インデックスのブロック変数iを与えてやることで、繰り返し処理にインデックスを振ることができる。 2022-02-20 23:07:29
GCP gcpタグが付けられた新着投稿 - Qiita GCP Associate Cloud Engineer 認定試験ガイド、ドキュメントリンク一覧 https://qiita.com/sensuikan1973/items/87dc6e782e6b732b4310 「製品を使用してデータシステムを初期化するCloudSQL、Firestore、BigQuery、CloudSpanner、PubSub、CloudBigtable、Dataproc、Dataflow、CloudStorageなど」CloudSQLインスタンスの作成DatastoreDatastoreモードのFirestoreでデータを保存し、クエリを実行するFirebaseCloudFirestoreを使ってみるBigQueryデータセットの作成CloudSpannerインスタンスの作成と管理CloudPubSubトピックとサブスクリプションの管理CloudBigtableインスタンスの作成Dataproc初期化アクションDataflowテンプレートを使用したクイックスタートCloudStorageストレージバケットの作成「データを読み込むコマンドラインによるアップロード、APIによる転送、インポートエクスポート、CloudStorageからのデータの読み込み、CloudPubSubへのデータのストリーミングなど」CloudStorageオブジェクトのアップロードCloudStorageオブジェクトのダウンロードCloudStorageTransferServiceTransferServiceforOnPremisesDataの概要TransferAppliance概要BigQueryDataTransferServiceBigQueryDataTransferServiceの概要CloudSQLデータのインポートとエクスポートのベストプラクティスDatastoreエンティティのエクスポートとインポートBigQueryデータのバッチ読み込みBigQueryテーブルデータのエクスポートDataflowPubSubを使用したストリーミングネットワーキングリソースをデプロイし、実装する。 2022-02-20 23:12:27
Ruby Railsタグが付けられた新着投稿 - Qiita 【Rails】繰り返し処理におけるインデックスについて https://qiita.com/miya114/items/4447adcbe66759e4d3ea 【Rails】繰り返し処理におけるインデックスについてeachdo文におけるインデックスhogehtmlerblthogeseachwithindexdohogeigtltdivdatacolumnsltigtgtlthogecontentgtltdivgtltendgt上記のように、eachdoをeachwithindexdoと記述し、インデックスのブロック変数iを与えてやることで、繰り返し処理にインデックスを振ることができる。 2022-02-20 23:07:29
技術ブログ Developers.IO GitHub Dependabotのセキュリティアラートが来たので対処してみた https://dev.classmethod.jp/articles/alert-for-github-dependabots-vulnerability-detection/ dependabot 2022-02-20 14:52:32
海外TECH MakeUseOf 6 Time Management Tips to Organize Your Own Workload https://www.makeuseof.com/time-management-tips-to-organize-workload/ management 2022-02-20 14:30:12
海外TECH DEV Community Why you should Learn Python in 2022 https://dev.to/digiakshay/why-you-should-learn-python-in-2022-19n2 Why you should Learn Python in Python is one of the greatly typically used languages and among its numerous applications are data mining AI web development embedded systems and many others Python is an outstanding choice for doing rapid prototypes which implies it s utilised by start ups to promptly establish their preliminary minimum attainable product MVP Python is one of the vastly highly scalable terminologies and is therefore utilized by many of the world s largest and most progressive businesses  Python ApplicationsThe language has become so prominent in recent times that aspirants are assembling to comprehend the language and develop Python programming skills We will be characterizing some of the most crucial real world applications of Python Web DevelopmentA python is a good option for the abrupt development of web applications With numerous frameworks like Django Pyramid and Flask Python authorizes you to build web apps with great speed Python is utilized on the server side of web development you can use Python to interact with the database and build Rest API services Data ScienceEarlier Python was primarily used for building applications and writing scripts to automate tasks but now an entirely new trend of data science has uplifted Python even more Data science people are heavily dependent on Python because of its objectives like simplicity great community and capabilities to compute huge calculations with ease Python libraries and frameworks that are popular in the data science field are Pandas  Data analysis Numpy  Numeric and scientific calculations Matplotlib Seaborn Data visualizations Scikit learn  Machine learning TensorFlow Keras Machine and Deep learning Artificial IntelligenceThe near future will be the time of artificial intelligence Computers and machines were utilized to accomplish mathematical calculations at very high speeds but presently many big institutions and researchers are labouring on building intelligent systems that can accomplish tasks as a human would To some extent machines are capable enough to comprehend human emotions and their natural language They can mimic certain actions accomplished by humans that were not possible before Again Python is outstanding for building AI systems Some Python libraries that are used for building intelligent systems are listed below NLTK  Natural language toolkit for Natural language processing OpenCV  Open source computer vision library Keras  Deep learning library Microsoft cognitive toolkit  Deep learning framework AutomationPython can make life easier by automating many tasks like scraping a website to collect data automating test cases in software development areas to automating mundane office tasks Python can easily access and browse all types of files which opens up an opportunity to save a lot of time by automating repetitive tasks The frameworks or libraries used for automation are Robot framework PyTest Selenium Python PyUnit Python is being utilized in diverse fields exceptionally and it shows no signs of stopping It is safe to conclude that Python will stick for the long run in this ever changing and evolving IT industry Why Learn Python To make it approachable for you we ve listed the top reasons why to learn Python It couldn t get simpler than Python The main reason why Python is an excellent choice for beginners is its born simplicity  Python s simple syntax it almost resembles English and high readability characteristics make it a beginner friendly language Naturally the learning curve of Python is way shorter than that of any other language Jave C C etc Further Python lets you go straight to your exploration part without worrying about the documentation   Python is highly flexible and extensiblePython is highly scalable and extensible This flexibility of Python enables you to accomplish cross language operations without any hassle Not only can you merge it with Java and NET components but you can also use Python to invoke C C libraries  Also almost all contemporary outlets like Windows Linux Macintosh Solaris etc support Python Python makes web development a breezeAnother purpose why to learn Python is that it creates the web development process so much easier Python comes with a wide variety of web development frameworks such as Django Flask Pyramid TurboGears WebPy Bottle CherryPy Hug Falcon Sanic and FastAPI to name a few   Best Python Training Institute In DelhiThese Python frameworks assist developers to write stable code much faster They can automate the execution of common standard solutions thereby decreasing the development time This enables developers to concentrate on more critical elements like application logic Apart from this Python frameworks can also accomplish web scraping tasks Python comes with numerous testing frameworksWhen it comes to testing or validating ideas products Python is the way to go It encompasses several built in testing frameworks that enable debugging amp speeding up workflows  Python supports both cross platform and cross browser testing with frameworks like PyTest and Robot There are also other testing frameworks like UnitTest Behave and Lettuce Python is excellent for Enterprise Application Integration EAI Python is an incredible choice for EAI It can be embedded in applications seamlessly and it also applies to applications written in other languages Case in point not only can Python invoke CORBA COM components but it can also directly call from and to Java C or C code The language features strong integration bonding with Java C and C which makes it excellent for application scripting  Python s text processing and integration abilities are highly commendable It can be used for developing GUI and desktop applications as well Python is backed by an active communityPython boasts of a vibrant and well knit community that you can rely on In case of any coding related or Data Science issues you can always seek help from the Python community They are ever ready to help people Since it is an open source language every day new growth is being made in the community developers and coders regularly contribute to endowing the language by developing new tools and libraries Python skills can command high salariesIf you have Python skills you can grasp high salaries in the industry Since Python rules the development and Data Science fields at present it promises a high growth graph with huge salary prospects 2022-02-20 14:45:24
海外TECH DEV Community Create a Reddit clone with RedwoodJS https://dev.to/arnu515/create-a-reddit-clone-with-redwoodjs-pcp Create a Reddit clone with RedwoodJSRedwood is an opinionated full stack javascript web application framework It is also serverless ready meaning it can be deployed on the edge with services like AWS Lambda and Cloudflare Workers Redwood is super opinionated It decides your project directory structure it decides the frameworks and libraries you use and it configures everything for you Some may see a downside to this but if you re experienced with Redwood s choosing of frameworks you will have a pleasant time using Redwood Redwood was created by Tom Preston Werner You may have heard of him before because he is the guy behindGithub which is the most popular code hostJekyll a ruby based static site generatorGravatar a very popular avatar serviceSemver the semantic versioning systemTOML a configuration language like JSON or YAML and much more PrerequisitesRedwood uses React for the frontend framework so you ll need to know React Redwood uses GraphQL instead of REST APIs so knowledge of that is required You can learn it on the official website Redwood uses Prisma for interacting with databases but it s very easy to use and you can pick it up from this tutorial itself Prisma works with SQL databases A Postgres database running You can either have the Postgres server installed or use Docker I ll be doing the latter in this tutorial There are various other libraries used like Jest and Storybook but these are not needed to follow this tutorial I ll be using TypeScript in this tutorial but feel free to use plain JavaScript Just be sure to remove any code that is TypeScript specific There are also a few things you ll need installed on your computer NodeJS v or higher I ll be using v Psst For an easy way to manage versions of NodeJS and many others try The Yarn Package Manager installed Redwood leverages yarn workspaces so yarn is needed You can install it using npm i g yarn A powerful code editor like VSCode or Neo Vim If you re using VSCode be sure to install the Redwood extension Step ーCreating your Redwood appOpen an empty folder in your favorite IDE and run the below command in the terminal yarn create redwood app If you re like me however and you ve fallen in love with TypeScript you can create a Redwood typescript app by adding the typescript flag to the above command like so yarn create typescript redwood app If you want to convert an existing Redwood project to TypeScript you can run yarn rw setup tsconfig and change your js files to ts Now open the project in your favorite IDE I ll use VSCode in this tutorial since Redwood has first class support for it Launch the editor and open the folder or just run code in the terminal You may be prompted to install recommended extensions so feel free to install them all or just some if you don t need certain extensions like Gitlens in my case Step ーGetting to know your projectLet s take a look at the project structure There are a few files in the root project Most of them are configuration files like jest config js Let s take a look at a specific file called redwood toml web title Redwood App port apiUrl redwood functions you can customise graphql and dbauth urls individually too see api paths includeEnvironmentVariables any ENV vars that should be available to the web side see web api port browser open trueRedwood recommends so many extensions but not a TOML one Install this extension for VSCode for TOML highlighting If you re unfamiliar with TOML syntax don t worry I ll guide you through the config For now let s change the port of both the web and api projects to and respectively Where your code livesThere are many directories but the main two directories are web and api This is where your Redwood code lives As the name suggests web is the frontend project and api is the backend project These two directories are actually their own projects and Redwood uses Yarn Workspaces to link these two folders together Inside the web folder The web folder is a regular ol React application If you know react you should be able to read through the structure of this directory There are just a few things that are different In the src folder you can see three more subfolders components layouts and pages The components folder holds any re usable React components The layouts folder holds page layouts which are also React components and the pages folder which contains React components mapped to routes What is a keep file keep files are just files that are placed in empty directories so they get committed to a git project Git doesn t commit empty folders so keep files are created to make the folder not empty and hence get it committed These keep files don t even have to be called keep they can be called anything else but by convention they re called keep and gitkeep Inside the api folder The api folder is the backend server This is running fastify under the hood which is just a faster backend server than express There are a few config files and there are three subdirectories The db folder contains the schema prisma file which is the schema for your database models that is used by Prisma ORM The src folder contains all of your source code for the backend From the redwood documentation directives will contain GraphQL schema directives for controlling access to queries and transforming values functions will contain any lambda functions your app needs in addition to the graphql js file auto generated by Redwood This file is required to use the GraphQL API graphql contains your GraphQL schema written in a Schema Definition Language the files will end in sdl js lib contains a few files auth js starts as a placeholder for adding auth functionality and has a couple of bare bones functions in it to start db js instantiates the Prisma database client so we can talk to a database and logger js which configures well logging You can use this directory for other code related to the API side that doesn t really belong anywhere else services contains business logic related to your data When you re querying or mutating data for GraphQL known as resolvers that code ends up here but in a format that s reusable in other places in your application Start the server Let s start the server by running the below command yarn rw devYou should now see your application running on http localhost or http localhost if you didn t change the port in the config The backend will run on port or if you didn t change the port in the config If this is what you see you ve successfully created your redwood project Replacing SQLLite with Postgres SQLLite is the default database used by Redwood since it doesn t expect everyone to have a fully fledged database installed and running on their computer But SQLLite is a file system based database and it also lacks in features when compared to Postgres A file system based database isn t the best for production so let s switch over to Postgres Postgres needs to be installed on your computer You can download it and install it and have a system wide install of postgres or you can use Docker to containerize it which is easier to do You ll need docker installed however and you can get it from here Once docker is running you can create a postgres container using the command below docker run d p name postgres e POSTGRES PASSWORD YOUR STRONG PASSWORD postgresBe sure to replace YOUR STRONG PASSWORD to a strong password since that will be the password of your root account in postgres The above command will run the postgres image as a container with the name postgres with the name flag adds the environment variable POSTGRES PASSWORD to it with the e flag exposes port postgres default port back to the host with the p flag and finally it runs it in the background with the d flag Now create a new database in the fresh postgres container you just created Run the below command to get shell access to the container docker exec it postgres bashIf your shell prompt changed you now have the ability to run commands directly in the postgres container Now run the below command to create a new database createdb U postgres NAME OF YOUR DATABASEThe U postgres flag makes it run as the postgres user which is the default root user Change NAME OF YOUR DATABASE to anything you want In my case I changed it to reddit which means that a new database with the name reddit has been created for me Once that s done exit out of the shell by typing exit and hitting Enter Now that you have a postgres database you just need to tell Prisma to use it Open the env file in the project root and add the below code to it DATABASE URL postgres postgres YOUR STRONG PASSWORD localhost YOUR DATABASE NAMEBe sure to replace YOUR STRONG PASSWORD and YOUR DATABASE NAME with the relevant values And finally change the line that says provider sqlite to provider postgresql in the api db schema prisma datasource db provider postgresql url env DATABASE URL Step ーCreating Prisma modelsPrisma models are definitions for how your database tables will look like They are written in prisma s own model language in the schema prisma file If you re not familiar with this syntax don t fear since it looks similar to GraphQL syntax and I ll guide you with it Creating the User modelOpen the src db schema prisma file in the api project Let s delete the example UserExample project and replace it with our own User model model User id String id default cuid db VarChar username String unique email String unique password String db VarChar avatarUrl String map avatar url roles String default member bio String isBanned Boolean default false map is banned map users If you can t see any syntax highlighting be sure to install the Prisma extension for VSCode What the above Prisma code does is it creates a model named User A Prisma model is mapped to a table in the database which in this case will be users because of the map users These are the fields that will be created An id filed which will be the primary key denoted by id It will be a String with the VarChar datatype in Postgres Since VarChar isn t supported by all databases Prisma supports like MongoDB we have to use db VarChar instead of directly declaring it as a VarChar type The id will also be a generated CUID by default A CUID is a randomly generated string like a UUID A username and an email field both of which are Strings and are unique meaning no two users can have the same email or username By default a String will be mapped to Postgres Text datatype A password which is a String in Prisma but a VarChar in PostgresAn avatarUrl which is a String This will be accessed in JavaScript with avatarUrl but will be stored in the database as avatar url because of map I did this because Postgres follows snake casing while JavaScript follows camelCasing A roles which is a String which will contain a comma separated string of roles You could use an array here but I feel like that would be overkill for a field that would usually only have one role Also member is the default A bio which is an optional string nullable in database lingo This is indicated by the after String And finally isBanned which is a Boolean that defaults to false and is stored as is banned in the database Now you need to sync the models to your database Currently they re only present in the schema prisma file To create the tables in the database run the below command yarn redwood prisma migrate devYou can use the alias rw instead of redwood and that s what I ll be doing from now on Be sure to give it a meaningful name Treat it like a git commit the name should reflect the changes you ve made In this case we ve created a User model so I named it add user model Now your database will have a table called users with all these fields that you just defined Creating the Post modelNow it s time to create a model for holding our posts model Post id String id default cuid db VarChar title String content String hasMedia Boolean default false map has media mediaUrl String authorId String map user id db VarChar author User relation fields authorId references id map posts You may see a squiggly line under the author field Don t worry we ll solve that soon The fields in this model are pretty similar to the ones in the User model except they have different names There is one odd one out however and that is authorId This authorId field will point to the id of the User that created this post and this is denoted by the author User line It has an relation directive that relates the id field of User to the authorId field of Post Prisma also requires that we include a backref a field on the other table that points back to this one indicating the relation Since this will be a one to many OM relation i e one user can have many posts the post backref in the User model should be an array You can denote that by putting square brackets after the type just like in regular TypeScript model User id String id default cuid db VarChar username String unique email String unique password String db VarChar avatarUrl String map avatar url roles String default member bio String isBanned Boolean default false map is banned post Post Add this line to your User model This is the backref map users model Post id String id default cuid db VarChar title String content String hasMedia Boolean default false map has media mediaUrl String authorId String map user id db VarChar author User relation fields authorId references id map posts While we re at it let s also add a Comment model which will store comments on a post This model will have two relations ーboth OM ーone with the User model and the other with the Post model model User id String id default cuid db VarChar username String unique email String unique password String db VarChar avatarUrl String map avatar url roles String default member bio String isBanned Boolean default false map is banned post Post backref to Post comments Comment backref to Comment map users model Post id String id default cuid db VarChar title String content String hasMedia Boolean default false map has media mediaUrl String authorId String map user id db VarChar author User relation fields authorId references id comments Comment backref to Comment map posts Our comment modelmodel Comment id String id default cuid db VarChar content String authorId String map user id db VarChar author User relation fields authorId references id postId String map post id db VarChar post Post relation fields postId references id map comments You should notice that the fields that are in a relation have the same type as the field they re in a relationship with This is important since they ll be storing the same type of data Let s migrate our database Run the same command as before and this time you can give it a name directly in the command line with the name argument yarn rw prisma migrate dev name add post and comment modelsWith that our three basic models have been created Let s now use them in the Redwood project Step ーAdding authentication to your appRedwood makes it really easy to add authentication to your application It handles almost everything that is boring like sessions and stuff like that Let s use the Redwood CLI and sets up authentication for you Run the below command to do that yarn rw setup auth dbAuthThis will setup a local authentication provider that saves your users credentials on the database Redwood also supports some authentication as a service providers out of the box like Auth and Magic Read more about that here A few new files have been created You need to edit these files to make it work with your schema First let s edit src lib auth ts This file contains methods that are used by Redwood under the hood to determine if a user is authenticated and authorized to access a resource You only need to do one small edit make Redwood read the roles stored in the users table in the hasRole function But first let s make the getCurrentUser function return the whole user instead of just the user s id export const getCurrentUser async session gt return await db user findUnique where id session id In the above snippet I just removed the select from the query so it returns all fields of the user We can now use this in the hasRole function Change out the hasRole function to the one below export const hasRole roles roles AllowedRoles boolean gt if isAuthenticated return false If your User model includes roles uncomment the role checks on currentUser if roles if Array isArray roles the line below has changed if context currentUser roles return context currentUser roles split some role gt roles includes role if typeof roles string the line below has changed if context currentUser roles return context currentUser roles split includes roles roles not found return false return true This code should now check the roles in the database instead of returning false by default Adding some fields to the User model Redwood gives you a hashedPassword a salt a resetToken and a resetTokenExpiresAt to store in your database but the current User model can only store the password Let s change that by adding three new fields to the User model by changing the User model in schema prisma to this model User id String id default cuid db VarChar username String unique email String unique password String db VarChar added the below three lines salt String db VarChar resetToken String db VarChar resetTokenExp DateTime db Timestamptz avatarUrl String map avatar url roles String default member bio String isBanned Boolean default false map is banned post Post comments Comment map users If you were messing around and created a few users your migration will fail because salt is empty and salt is not allowed to be empty So just add default to the salt field in the schema to ensure that already existing users won t have null values for required fields Next migrate with the below command yarn rw prisma migrate dev name add fields to userOf course you can use your own migration name Next you ll need to generate types so Redwood knows about the new User yarn rw generate typesAnd finally you need to restart the dev server Press Ctrl C maybe twice to stop the current running dev server and run yarn rw dev to start it again Configuring authentication There are just a few final changes you need to make to the src functions auth ts file such as setting an avatarUrl For the avatarUrl we ll use Gravatar which is a popular avatar service For that you just need to use the below URL as the avatarUrl s The EMAIL HASH should be an md hash of the user s email For generating an md hash let s install the md package along with its typescript definitions with the below commands yarn workspace api add md amp amp yarn workspace api add D types mdWe re using workspace api add instead of just add because there are two workspaces here and we just want to add md to the api folder not the web folder Now let s change the src functions auth ts file to make sure it works with our requirements import db from src lib db import DbAuthHandler from redwoodjs api import md from md export const handler async event context gt const forgotPasswordOptions handler is invoked after verifying that a user was found with the given username This is where you can send the user an email with a link to reset their password With the default dbAuth routes and field names the URL to reset the password will be user resetToken Whatever is returned from this function will be returned from the forgotPassword function that is destructured from useAuth You could use this return value to for example show the email address in a toast message so the user will know it worked and where to look for the email handler user gt return user How long the resetToken is valid for in seconds default is hours expires errors for security reasons you may want to be vague here rather than expose the fact that the email address wasn t found prevents fishing for valid email addresses usernameNotFound Email not found if the user somehow gets around client validation usernameRequired Email is required const loginOptions handler is called after finding the user that matches the username password provided at login but before actually considering them logged in The user argument will be the user in the database that matched the username password If you want to allow this user to log in simply return the user If you want to prevent someone logging in for another reason maybe they didn t validate their email yet throw an error and it will be returned by the logIn function from useAuth in the form of message Error message handler user gt return user errors usernameOrPasswordMissing Both email and password are required usernameNotFound Email username not found For security reasons you may want to make this the same as the usernameNotFound error so that a malicious user can t use the error to narrow down if it s the username or password that s incorrect incorrectPassword Incorrect password for username How long a user will remain logged in in seconds expires const resetPasswordOptions handler is invoked after the password has been successfully updated in the database Returning anything truthy will automatically logs the user in Return false otherwise and in the Reset Password page redirect the user to the login page handler user gt return user If false then the new password MUST be different than the current one allowReusedPassword true errors the resetToken is valid but expired resetTokenExpired resetToken is expired no user was found with the given resetToken resetTokenInvalid resetToken is invalid the resetToken was not present in the URL resetTokenRequired resetToken is required new password is the same as the old password apparently they did not forget it reusedPassword Must choose a new password const signupOptions Whatever you want to happen to your data on new user signup Redwood will check for duplicate usernames before calling this handler At a minimum you need to save the username hashedPassword and salt to your user table userAttributes contains any additional object members that were included in the object given to the signUp function you got from useAuth If you want the user to be immediately logged in return the user that was created If this handler throws an error it will be returned by the signUp function in the form of error Error message If this returns anything else it will be returned by the signUp function in the form of message String here handler payload gt const username email hashedPassword salt userAttributes payload return db user create data email password hashedPassword avatarUrl md email d mp amp s salt salt username userAttributes name errors field will be either username or password fieldMissing field is required usernameTaken Email username already in use const authHandler new DbAuthHandler event context Provide prisma db client db db The name of the property you d call on db to access your user table ie if your Prisma model is named User this value would be user as in db user authModelAccessor user A map of what dbAuth calls a field to what your database calls it id is whatever column you use to uniquely identify a user probably something like id or userId or even email authFields id id username email hashedPassword password salt salt resetToken resetToken resetTokenExpiresAt resetTokenExp forgotPassword forgotPasswordOptions login loginOptions resetPassword resetPasswordOptions signup signupOptions return await authHandler invoke All I did above was change the hashedPassword field to password and the username field to email I also replaced instances of Username in messages to Email and I added the avatarUrl field Adding login and signup pagesLet s add login and signup pages to the frontend Redwood makes this really easy by providing a generator for us Run the below command to create a login page a signup page and a forgot and reset password page yarn rw g dbAuthI will delete the ForgotPassword and ResetPassword pages since I won t be adding that functionality to this project Next you need to replace the username field in both Login and SignUp to email and in SignUp add a new field called username I ve done it below and here s how your code should look like Routes tsximport Router Route from redwoodjs router const Routes gt return lt Router gt lt Route path login page LoginPage name login gt lt Route path signup page SignupPage name signup gt lt Route notfound page NotFoundPage gt lt Router gt export default Routes LoginPage tsximport Link navigate routes from redwoodjs router import useRef from react import Form Label TextField PasswordField Submit FieldError from redwoodjs forms import useAuth from redwoodjs auth import MetaTags from redwoodjs web import toast Toaster from redwoodjs web toast import useEffect from react const LoginPage gt const isAuthenticated logIn useAuth useEffect gt if isAuthenticated navigate routes home isAuthenticated const emailRef useRef lt HTMLInputElement gt useEffect gt emailRef current focus const onSubmit async data gt const response await logIn data if response message toast response message else if response error toast error response error else toast success Welcome back return lt gt lt MetaTags title Login gt lt main className rw main gt lt Toaster toastOptions className rw toast duration gt lt div className rw scaffold rw login container gt lt div className rw segment gt lt header className rw segment header gt lt h className rw heading rw heading secondary gt Login lt h gt lt header gt lt div className rw segment main gt lt div className rw form wrapper gt lt Form onSubmit onSubmit className rw form wrapper gt lt Label name username className rw label errorClassName rw label rw label error gt Email lt Label gt lt TextField name username className rw input errorClassName rw input rw input error ref emailRef validation required value true message Email is required gt lt FieldError name username className rw field error gt lt Label name password className rw label errorClassName rw label rw label error gt Password lt Label gt lt PasswordField name password className rw input errorClassName rw input rw input error autoComplete current password validation required value true message Password is required gt lt FieldError name password className rw field error gt lt div className rw button group gt lt Submit className rw button rw button blue gt Login lt Submit gt lt div gt lt Form gt lt div gt lt div gt lt div gt lt div className rw login link gt lt span gt Don amp apos t have an account lt span gt lt Link to routes signup className rw link gt Sign up lt Link gt lt div gt lt div gt lt main gt lt gt export default LoginPageimport Link navigate routes from redwoodjs router import useRef from react import Form Label TextField PasswordField FieldError Submit from redwoodjs forms import useAuth from redwoodjs auth import MetaTags from redwoodjs web import toast Toaster from redwoodjs web toast import useEffect from react const SignupPage gt const isAuthenticated signUp useAuth useEffect gt if isAuthenticated navigate routes home isAuthenticated focus on email box on page load const emailRef useRef lt HTMLInputElement gt useEffect gt emailRef current focus const onSubmit async data gt const response await signUp data if response message toast response message else if response error toast error response error else user is signed in automatically toast success Welcome return lt gt lt MetaTags title Signup gt lt main className rw main gt lt Toaster toastOptions className rw toast duration gt lt div className rw scaffold rw login container gt lt div className rw segment gt lt header className rw segment header gt lt h className rw heading rw heading secondary gt Signup lt h gt lt header gt lt div className rw segment main gt lt div className rw form wrapper gt lt Form onSubmit onSubmit className rw form wrapper gt lt Label name username className rw label errorClassName rw label rw label error gt Email lt Label gt lt TextField name username className rw input errorClassName rw input rw input error ref emailRef validation required value true message Email is required gt lt FieldError name username className rw field error gt lt Label name name className rw label errorClassName rw label rw label error gt Username lt Label gt lt TextField name name className rw input errorClassName rw input rw input error ref emailRef validation required value true message Username is required gt lt FieldError name name className rw field error gt lt Label name password className rw label errorClassName rw label rw label error gt Password lt Label gt lt PasswordField name password className rw input errorClassName rw input rw input error autoComplete current password validation required value true message Password is required gt lt FieldError name password className rw field error gt lt div className rw button group gt lt Submit className rw button rw button blue gt Sign Up lt Submit gt lt div gt lt Form gt lt div gt lt div gt lt div gt lt div className rw login link gt lt span gt Already have an account lt span gt lt Link to routes login className rw link gt Log in lt Link gt lt div gt lt div gt lt main gt lt gt export default SignupPageNotice how I ve only changed the text but not the name of the inputs This is because under the hood Redwood still expects your email to be called username For one final step let s add a home page so we don t have to see the Redwood logo anymore Use the below command to generate an index page at yarn rw g page home This command will generate a page called home but map it to instead of home Change the code of the newly created HomePage tsx to this import MetaTags from redwoodjs web const HomePage gt return lt gt lt MetaTags title Redwoodit description A clone of Reddit using RedwoodJS gt lt h gt Redwoodit lt h gt lt gt export default HomePageAnd with that you ve added authentication to your Redwood application If you visit http localhost signup you can create an account and if you visit http localhost login you can log in to an account ConclusionYou ve successfully created a Redwood application and added authentication to it In the next part of this tutorial you will add support for fetching creating updating and deleting posts and comments If you ve gotten stuck anywhere be sure to check out the source code the Redwood documentation or ask in the Redwood Discord Discourse Forums for help Stay tuned for Part 2022-02-20 14:41:46
海外TECH DEV Community Randomness and Cryptography https://dev.to/prakhart111/randomness-and-cryptography-52pd Randomness and Cryptography Hey everyoneI am back with The Random series One of my most loved and my personal favourite as well This series has overall got almost K viewson various platforms like Dev Community HashNode and TealFeed I will recommend you to read the previous article before reading this oneIs random really random So let s dive in Before diving into the cryptographic aspect of randomness we first need to understand what actually cryptography is and how it works So Wikipedia saysCryptography or cryptology is the practice and study of techniques for secure communication in the presence of adversarial behaviour And that was a very bookish type of definition Okay so cryptography is basically some sort of encryption for the data being transferred that means only the sender and receiver can view the data or the message and ideally no one else not even ZuckerBurg lol And yeah its actually kind of more ideal version of what WhatsApp claims to provide “END TO END ENCRYPTION NOTECryptography is a subject that involves a lot of high end mathematics and hence I will try to avoid those complex expressions and keep it as simple as it can be This is closely related to encryption which is the act of scrambling ordinary text into what s known as cipher text and then back again upon arrival Some very common examples of encryption can be Encryption over the internet like the SSL Wireless G LTE network uses bit Advanced Encryption Standard AES and SNOWGYour Internet banking cards UPI payments etc Encryption in your computer like storing passwords files etc If you have ever heard of the famous Ceaser Cipher you will probably be able to connect with the idea of cryptography If you haven t read it here How Encryption worksIn case of encryption a given algorithm will always transform the same plain text into the same cipher text if the same key is used Key is basically some number that is used while encoding and decoding So let s have an example Say we take KEY and we decided to encode our message in such a way that every English alphabet is replaced by the KEY th alphabet That means in our example A to be replaced by C B to be replaced by D and so on And a simple assignment Comment down what is the below message based on the above description Key Kpetgfkdng Kpfkc Note Special characters remain the same in Caesar Cipher So this can be the simplest form of encryption There are two types of cryptography symmetric and asymmetric Symmetric CryptographyWith symmetric cryptography the same key is used for both encryption and decryption A sender and a recipient must already have a shared key that is known to both So just have a thought you are also sending the decryption key via the same channel that can obviously be intervened I mean hackers are damn smart nowadays Although any hacker won t be interested in reading your efforts and super fast replies towards your crush even after getting ignored so you can relax emotional damage to me as well Asymmetric CryptographySo yes these security concerns lead to the development of next type that is Asymmetric Here we have two different keys PUBLIC KEY and a PRIVATE KEY Private key as the name suggests is always private to whom it belongs and his public key is available to all Data encrypted with a public key may only be decrypted with the corresponding private key Let s have an example Suppose you are Raju want to send a message to your friend Baburao about a great financial scheme So you need to have his public key and encrypt the message using it and send it to him Only Baburao can decrypt the message as only he has his private key And similarly any data encrypted with a private key can only be decrypted with the corresponding public key Let s dive even deep with a easier real world example So basically we want an encryption method that is easy to do on one side but difficult from the other side i e encrypting is easy but decryption without required information is very difficult Here we can use a simple yet great mathematical trick that actually powers the modern world not as it is though is Prime Numbers Say you multiply two prime numbers and that would be Very Simple isn t it Now have a look in the opposite direction You have given and you need to find exact those prime numbers we used to encrypt it This will take you a while I mean you will look at different possible prime combinations as so on But now what if I say those numbers will be something huge like or Multiplication encryption would be fairly easy but decryption will take a lottt of time Now let s get back to the Random Numbers The key has to be random Randomness as it is used to generate session keys The more random the numbers the more secure the cryptographic system And here comes the problem that we discussed in our previous article computers cannot provide pure randomness Hence we use cryptographically secure pseudo random number generator that are based on external entropy the best source of which is Quantum Physics Quantum Random Number Generators QRNGs are able to provide highest possible randomness till date In its latest report looking at quantum computing the IBM Institute for Business Value highlights the potential quantum technologies have to become a double edged sword one that will expand computing power and offer opportunities for improving cyber security whilst exposing vulnerabilities in current encryption methods HashingThere exists another similar term HASHING Hashing is the process of converting the information into a unique text using a hash function The original information cannot be retrieved from the hash key by any means Most popular algorithm for this is SHA In this no matter how large your input data is the resulting Hash will always be of characters If you people are interesting in knowing about hashing more let me know in the comments below Here are some resources that you can have a look at to gain more insights about Cryptography Cryptography Concepts every developer should know by FireShipA TED from James Lyne Power of randomnessI found the below ones bit advanced QRNG White PaperTrue Randomness Thanks for reading If you loved the article please share it it takes a lot of efforts and time making The Random series Want to connect You can connect with me here 2022-02-20 14:04:09
Apple AppleInsider - Frontpage News Nearly every Mac rumored to see an update in 2022 https://appleinsider.com/articles/22/02/20/nearly-every-mac-rumored-to-see-an-update-in-2022?utm_medium=rss Nearly every Mac rumored to see an update in Apple will be bringing out a minimum of seven Mac models with Apple Silicon with a large screened iMac Pro and a revamp of the Mac Pro among the inbound updates An updated Apple Silicon Mac Pro may be half the size of the last Intel based model Apple is on a self imposed two year transition from Intel processors to its own Apple Silicon by the end of In a bid to complete the shift Apple has to make a few more changes to its product range alongside its normal upgrades to existing models Read more 2022-02-20 14:45:28
Apple AppleInsider - Frontpage News Daily deals Feb. 20: $250 Oculus Quest 2, Half-Price Amazon Fire 7 Kids, more https://appleinsider.com/articles/22/02/20/daily-deals-feb-20-250-oculus-quest-2-half-price-amazon-fire-7-kids-more?utm_medium=rss Daily deals Feb Oculus Quest Half Price Amazon Fire Kids moreSunday s top deals include the Amazon Fire Kids Pro Tablet for MSI s Vigor GK RGB Keyboad for and a free Target gift card when you buy a Apple gift card Best Deals for February Just like we do every day we ve collected some of the best deals we could find on Apple products tech accessories and a wealth of other products to help you save money If an item is out of stock you may still be able to order it for delivery at a later date Read more 2022-02-20 14:03:43
ニュース BBC News - Home The Queen tests positive for Covid https://www.bbc.co.uk/news/uk-60453566?at_medium=RSS&at_campaign=KARANGA buckingham 2022-02-20 14:14:20
ニュース BBC News - Home Storm Franklin: More wind warnings after Storm Eunice https://www.bbc.co.uk/news/uk-60452334?at_medium=RSS&at_campaign=KARANGA warnings 2022-02-20 14:47:43
ニュース BBC News - Home DUP MLA Christopher Stalford dies aged 39 https://www.bbc.co.uk/news/uk-northern-ireland-60451845?at_medium=RSS&at_campaign=KARANGA deputy 2022-02-20 14:23:51
ニュース BBC News - Home Ukraine crisis: Russia keeps troops in Belarus amid Ukraine fears https://www.bbc.co.uk/news/world-europe-60451955?at_medium=RSS&at_campaign=KARANGA moscow 2022-02-20 14:50:41
ニュース BBC News - Home Winter Olympics close with plea for peace https://www.bbc.co.uk/sport/winter-olympics/60451409?at_medium=RSS&at_campaign=KARANGA athletes 2022-02-20 14:01:07
ニュース BBC News - Home Boris Johnson: Do not throw caution to the wind on Covid https://www.bbc.co.uk/news/uk-60446908?at_medium=RSS&at_campaign=KARANGA legal 2022-02-20 14:45:56
ニュース BBC News - Home Jack Ritchie inquest: Parents hope for gambling laws change https://www.bbc.co.uk/news/uk-england-south-yorkshire-60433095?at_medium=RSS&at_campaign=KARANGA death 2022-02-20 14:48:46
サブカルネタ ラーブロ 手しごとの店 ちくら 新潟駅前の居酒屋が提供するあっさり煮干し醤油 http://ra-blog.net/modules/rssc/single_feed.php?fid=196656 手しごとの店ちくら新潟駅前の居酒屋が提供するあっさり煮干し醤油新潟市中央区、新潟駅前にある「手しごとの店ちくら」へと行ってきました。 2022-02-20 14:36:34
北海道 北海道新聞 次回26年大会に五輪旗引き継ぎ ミラノなどイタリア2都市で開催 https://www.hokkaido-np.co.jp/article/648069/ 引き継ぎ 2022-02-20 23:20:00
北海道 北海道新聞 「五輪の団結、平和的機会に」 バッハ会長が閉会式であいさつ https://www.hokkaido-np.co.jp/article/648068/ 国際オリンピック委員会 2022-02-20 23:16:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)