teleren/devto huggingface dataset:
|YelpCamp| Adding in Authentication
Tags: javascript, html, css, webdev
Published: 2020-12-28 00:40:45

---
title: |YelpCamp| Adding in Authentication 
published: true
description: 
tags: javascript, html, css, webdev
//cover_image: https://direct_url_to_image.jpg
---

                   -Introduction to passport 
                   -Creating Our User Model 
                   -Configuring Passport 
                   -Register Form 
                   -Register Route Logic
                   -Login Routes
                   -isLoggedIn Middleware
                   -Adding Logout 
   


###Introduction to passport 
http://www.passportjs.org/

Passport is a library that helps add authentication into node apps. 


###Creating Our User Model
Create a new user.js file 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/iclowvb6h7pffhzegnoq.png)



 
###Configuring Passport 

Implementing serialization in the app.js file 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hra64k2wa1ou8u3vithc.png)


```javascript

passport.serializeUser(User.serializeUser())

```

Tells passport how to serialize a user. Serialization is how session is stored. 

```javascript 

passport.deserializeUser(User.deserializeUser();

```
Is how to get out of sterilization. 

###Register Form 
Creating the register form in users.js 

```javascript 

const router = express.Router(); 
const User = require('../models/user'); 
const { remove } = require('../models/user'); 

router.get('/register', (req, res) => {
  res.render('users/register');
 });
 router.post('/register', async(req, res) => {
    res.send(req.body);
 })

module.exports = router; 

```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/pjidp7rzx2uebcnwtb31.png)


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3nvgr15fi5y7zcpzbkks.png)

###Register Route Logic

```javascript 

router.post('/register', catchAsync (req, res) => {
try {
  const { email, username, password } = req.body; 
  const user = new User({ email, username}); 
  const registeredUser = await User.register(user, password);
  req.flash('success', 'Welcome to Yelp Camp!'); 
 } catch(e) {
   req.flash('error', e.message);
   res.redirect('register');

  }));

module.exports = router; 

```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gjam7jg36awa33u12ybq.png)



###Login Routes

```javascript

router.get('/login', (req, res) => {
   res.render('users/login');
})

router.post('/login', passport.authenticate('local' { failureFlash: true, failureRedirect: '/login' }), (req, res) => {
   req.flash('success', 'welcome back!'); 
   res.redirect('/campgrounds');
})

```









###isLoggedIn Middleware

```javascript 

module.exports.isLoggedIn = (req, res, next) => {
  if (!req.isAuthenticated()) {
     req.flash('error', 'You must be signed in first!'); 
     return res.redirect('/login');
  }
 next(); 
}

```


###Adding Logout 

```javascript 

router.get('/logout', (req, res) => {
  req.logout(); 
  req.flash('success', 'Goodbye!');
  res.redirect('/campgrounds'); 
 })
```
How I feel looking for my first job explained with code.
Tags: firstpost, job, javascript
Published: 2020-12-28 00:47:21

Hi my name is Juan and I'm a computer science student looking for my first job as a developer, so far I'm doing good in the technical interviews, but when they ask me about my experience I feel like this:
```
function getFirstJob(programmer) {
  if(programmer.hasExperience) {
    return "you are hired"
  }
  getExperience(programmer)
}

function getExperience(programmer) {
  getFirstJob(programmer)
}

```
And you know what happens when you run getFirstJob(). So far  I couldn't get out of that loop. I would like to get advice or your comments if you are going through a similar situation. Thanks for reading, have a great day :)
Use case when to use Webpack VS Gulp? 
Tags: webpack, gulp, javascript
Published: 2020-12-28 00:38:34

I have tried to Google it, but I get a lot of old posts from reddit which is 2017. We are almost 2021 and I'm pretty sure things have changed compared to 4 years ago. Are there any reasons to use Gulp today, or should you just discard using Gulp and move to Webpack 5 because it's better? If so, what's better?
How to get the directory of the currently executing script in Node.js?
Tags: node
Published: 2020-12-28 00:00:00

---
  title: How to get the directory of the currently executing script in Node.js?
  published: true
  tags: Nodejs
  date: Mon Dec 28 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/get-directory-of-currently-executing-script-nodejs
  cover_image: https://melvingeorge.me/_next/static/images/main-0d463f4191af9a17642cbc84e8c82653.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/get-directory-of-currently-executing-script-nodejs)
  
To get the directory of the currently executing script, you can use the `__dirname` environment variable in Node.js

For example, let's say we have a file called `myscript.js` inside a directory called `scripts`.

Inside this `myscript.js` file let's log the value of the `__dirname` environment variable like this,

**scripts/myscript.js**

```js
console.log("Script executing in directory:", __dirname);
```

If we were to execute the script using the command `node scripts/myscript.js` from the terminal, we would get the full absolute path to the script file

```bash
Script executing in directory: /Users/bob/scripts
```

like this.

See this example live in [repl.it](https://repl.it/@melvin2016/get-current-directory-of-executing-script-nodejs#index.js).

### Feel free to share if you found this useful 😃.

---
🎉 Frontendor UI Library v2.0 - Happy Holidays Deal
Tags: webdev, html, css
Published: 2020-12-27 23:56:23

Hey! Happy Holidays 🎉🎉🎉

We want to celebrate more with you and that is why we want to offer a ~25% OFF discount: https://gumroad.com/l/f50/f25?variant=Full%20Package

We’re excited to announce the Frontendor Library 2.0, which is a library of 100+ UI blocks built with bootstrap (responsive, customizable, and easy to integrate) & 6+ templates (will add more regularly), and you can use it for personal and commercial use in unlimited projects for just a one-time investment.

No more hassles and no need to think about design and inspiration because it lets you construct gorgeous landing pages with an excellent user experience in both mobile and desktop, quickly and easily by using a simple Copy-Paste method.

Now we’ve added a bunch of cool new features and made some major improvements. Here are our top recent updates that we’re especially excited about:

- Rebuilt all blocks with a new design.
- 100+ UI blocks built with bootstrap 
- We added dropdowns and mega menus to Hero’s navigation.
- Sticky navigation on the scroll.
- The copy-paste tool is online forever, no need to download it again (this way we can update it easily).
- Completely new brand templates.
- A lot of bugs got fixed.

Sounds interesting? Then get your ~25% OFF discount: https://gumroad.com/l/f50/f25?variant=Full%20Package
A simple explanation of 'this' - JavaScript
Tags: javascript, beginners, programming
Published: 2020-12-27 23:15:38

![Yellow background with black text "JavaScript 'this'"](https://dev-to-uploads.s3.amazonaws.com/i/0fmgee6w6b0y0iv2vltm.png)

'this' is a property of an execution context

In <strong>non–strict mode</strong>, 'this' refers to the Object that is executing the current function.

In <strong> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode" trget ="_blank">strict mode</a></strong>, 'this' can be any value.

The value of 'this' depends on the context in which it is used. Let's dive in!

<h3>Global Context</h3>

When 'this' is used globally, (meaning it is not within a method or function) it automatically refers to the window object.

```js
console.log(this); // {window Object}
```

<h3>Function Context</h3>

<h4>Regular Function Context</h4>

'this' within a regular function that is not part of an Object also refers to the window Object as shown below 

```js
const showThis = () => {
    console.log(this); // {window Object}
}

//In strict mode, however, if the value of this is not
// set when entering an execution context, it remains as undefined, as shown in the following example:

const showThis = () => {
    'use strict'; // see strict mode
    console.log(this); // undefined
}
```
<h4>Constructor Function Context</h4>

When using the constructor function to create a new object, the 'new' operator creates an object and points 'this' to the newly created object.

```js
function Series (title) {
    this.title = title;
    console.log (this); // {Newly created Object}
}

const v = new Series ('The Office');  //  Create new Object using constructor function.
```

<h3>Method Context</h3>

A method is a function that is part of an Object.

'this' within a method refers to its parent Object.

```js
const things = {
    roses: 'red',
    sky: 'blue',
    snow:'white',
    showColor(){
        console.log(this); // {things Object}
        console.log(this.roses); // 'red'
    }
};
```

A callback function within a method would refer to the window Object unless a 'this' argument aka <i>thisArg</i> is provided.


The <i>thisArg</i> is an optional value to use as 'this' when executing callback function. Take a look at how this works using the forEach array method.


```js
Syntax 
// arr.forEach(callback(currentValue) {
//   // execute something
// }, [thisArg]);

const random = {
    title: 'Primary',
    colours: ['red'],
    showColours ()){
        this.colours.forEach(colour => {
            console.log(this.heading, colour) // Rosy red
        }, { heading: 'Rosy' }) // optional 'this' argument
    }
};
```
That's all folks, see you next week!

<a href="https://lindaojo.com/articles" target="_blank">Read other articles
</a>
I launched a directory with ethical design resources
Tags: showdev, ethics, design, sideprojects
Published: 2020-12-27 23:40:11

Tech is all around us, developing fast, and not going away. Which is why ethics should be a part of the design and engineering curriculum, and a focus for everyone working in the industry.

Earlier this year I wrote about what it's like [navigating the internet as a non-binary person](https://fossheim.io/writing/posts/non-binary-design/) and [the harm transphobic AI can cause](https://fossheim.io/writing/posts/ai-bias-genderify/).

There were also stories about [social media apps using facial recognition failing trans people](https://www.theverge.com/2020/2/7/21128236/gender-app-giggle-women-ai-screen-trans-social), [algorithms keeping students out of college](https://www.wired.com/story/algorithm-set-students-grades-altered-futures/), [software that can depixelate faces](https://twitter.com/tg_bomze/status/1274098682284163072?lang=en), [surveillance AI](https://thegradient.pub/how-the-police-use-ai-to-track-and-identify-you/), fake news around COVID and the US elections, and countless more examples of tech failing the people.

This is nothing new, and should not be surprising. Tech isn't neutral. It's made by people and consumed by people. People write algorithms, collect training data, design websites, write code and prioritize features.

Countless of books, articles and even documentaries have been made about the issue, and there are plenty of resources out there that can educate us on the issues the tech industry is facing and can guide us to do better.

So I decided to build a directory that lists them: [ethicaldesign.guide](https://ethicaldesign.guide)!

![Screenshot of ethicaldesign.guide: a description on top, recommended topics on the left, and resources on the right](https://dev-to-uploads.s3.amazonaws.com/i/xxqfxjuoinoy0qw77670.png)

It's a growing directory of tools, articles, books, podcasts, and other learning resources to guide us in creating more ethical and more inclusive products. I'll be editing it continuously with new resources ([and anyone can suggest a resource](https://ethicaldesign.guide/submit/), so keep an eye out on the page or subscribe to the [mailing list](https://www.getrevue.co/profile/ethicaldesignguide) to receive a monthly update on new resources and interesting reading material.

Originally posted on [fossheim.io](https://fossheim.io/writing/posts/ethical-design-guide/)
Week 1 of Colt Steele Course
Published: 2020-12-27 23:13:21

I jumped straight to bootstrap section. I was amazed by the way Colt Steele teaches. Somehow it’s easy for me to understand him. I have attended a JavaScript bootcamp in the past (they fully made us use code.org). The bootcamp was in person but it wasn’t as easy to understand as the way Colt Steele teaches. 

Before starting bootstrap section the only thing I knew about bootstrap was bootstrap buttons. It took me around 4-5 hours to go through bootstrap section. I learned how to add padding and margins and much more. I understand how to make browsers responsive by using for example container/container-fluid, row and col (column). I’m planning to eventually take his bootstrap course after I finish this bootcamp.

I moved on to candy museum project the next day. I created an ice cream store website using the skills learned from candy museum project. 

I have now moved on to the next section which is JavaScript.
A(nother) Todo List
Tags: javascript, noframework
Published: 2020-12-27 23:09:55

I've been working on the web since 2001, when I first got in to HTML, CSS, and Javascript. The internet of 2001 is not the same internet that we have today, and that is in no small part to the updates of all three of the web's technologies. However, with this growth has come some changes in how people actually develop for the web: frameworks.

When I started there was nothing fancy-- If you wanted to do things in Javascript you needed to learn how to use Javascript and the Document Object Model (DOM). This was ... well quite honestly it was awful, and honestly it's still not _great_ -- but it is doable.

Normally, I don't tend to think about this anymore. I trust that the teams responsible for the frameworks I use put much more time in caring how they deal with the DOM on a webpage than I ever will. However, I am active in places like StackOverflow and Quora. Recently, on Quora I saw a question that I've seen many times, and that I've ignored just as many times:

> Why should I learn (React / Angular / Vue / another framework or library)?

The other day when I read the first thing I said internally was "because most people don't want to have to deal with the DOM themselves." While that statement might be broadly correct, it occurs to me that I know plenty of people who can work in React or Vue or Angular, but who would absolutely have no idea how to build the same functionality in a framework-less world.

I had started writing a response when an idea hit me: "Instead of just telling them about how dealing with the DOM is annoying, just make a quick app that doesn't use anything outside of pure JS."

So, I did. I call the project "Vanilla Todo" and in it I have attempted to imagine myself as someone who is a recent entry into the world of web development, and that they are somehow unaware of the many frameworks and libraries that now live on the front end.

Each branch of Vanilla Todo will progress through stages that I myself can remember hitting when I was new to the web. The first branch is "version 1" or "I put this together in a craze and it works!". Each branch from there will modify the repository, both in code structure and in implementation, until such time that I (hope) a new user will understand why people have flocked to front-end frameworks.

The repository is still in it's earlier stages, with two branches being overall done, and I am working on others as we speak.

The link for the repository is [gitlab.com/jhechtf/vanilla-todo](https://gitlab.com/jhechtf/vanilla-todo).

I will be making posts to talk about each branch in a bit more detail, and possible things that people could do to try out different ways of dealing with the DOM.
How do you manage the content for your portfolio?
Tags: watercooler, portfolio, productivity
Published: 2020-12-27 22:59:11

---
title: How do you manage the content for your portfolio?
published: true
description: 
tags: watercooler, portfolio, productivity
cover_image: https://www.opensourcecms.com/wp-content/uploads/How-to-Choose-a-Content-Management-System.jpg
---
A nice portfolio is a must-have for any developer. Having it frequently updated is equally important to make it appealing for requiters. How do you manage content in your portfolio? 

Do you use some CMS like Sanity, Strapi, Contentful, Netlify CMS, Ghost, or Forestry?

Maybe you don't have set up any CMS or written any GUI for it and you do still update the local code directly and then push it?

Or maybe you have automatized the process by fetching data from GitHub, DEV, etc, so you don't have to worry about it at all?
|Authentication| From Scratch
Tags: javascript, html, css, webdev
Published: 2020-12-27 22:47:51

---
title: |Authentication| From Scratch 
published: true
description: 
tags: javascript, html, css, webdev
//cover_image: https://direct_url_to_image.jpg
---

                  -Authentication vs. Authorization 
                  -How to not store passwords
                  -Cryptographic Hashing Functions 
                  -Password Salts
                  -Intro to Bcrypt 



###Authentication vs. Authorization 
####Authentication
Is the process of verifying who a user is. 
Username and password is a typical authentication combo, as well as security questions and facial recognition. 

####Authorization
Is verifying what a specific user has access to. 
Now that we know who you are, this is what you are allowed to do or not allowed to do. 






###How to not store passwords
Rule 1 is to never store passwords in text within the database. 

This is what a stored password in text looks like. 

```javascript 

{
 
  username: 'kittykat', 
  password: 'notpassword123!'

},

 ```

Hashing is when a password is run through a hashing function and then stored the result in the database. 


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gbwr5g0rvq6d03s1jo71.png)


###Cryptographic Hashing Functions 


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/e60o9cnn7wb8tr4lpuho.png)

Cryptographic hash functions are one-way functions that is infeasible to invert. Small changes in input yields large change in the output. Deterministic - same input yields same output. Unlikely to find 2 outputs with the same value. Password has functions are deliberately slow. 


###Password Salts
A salt is a random value that is added to the password before it is hashed. 



###Intro to Bcrypt 


{% github kelektiv/node.bcrypt.js %}

to install bcrypt at the terminal 

```javascript 

npm i bcrypt 

```

to hash a password 

```javascript 

bcrypt.genSalt(saltRounds, function(err, salt) {
   bcrypt.hash(myPlainTextPassword, salt, function(err, hash) {
    });
  }); 

```
This generates a salt and hash on separate function calls. 


Within an app 

```javascript 


const bcrypt = require('bcrypt'); 

const hashPassword = async (pw) => {
   const salt = await bcrypt.genSalt(12); 
   const hash = await bcrypt.hash(pw, salt); 
   console.log(salt); 
   console.log(hash); 
}

const login = async (pw, hashedPassword) {
  const result = await bcrypt.compare(pw, hashedPassword) 
  if(result) {
    console.log("Logged In, Success!"); 
 } else {
    console.log("Incorrect"); 

 }
}

hashPassword('monkey'); 

```
Scan.co.uk sales scraper
Tags: python, beginners, beautifulsoup, scraping
Published: 2020-12-27 22:44:22

I was working today on a scraper that grabs the sale items from Scan.co.uk and collects the data in .csv file. Nothing fancy - its sole value is educational. And fittingly, the simple bs4 script threw up two issues that seem worth mentioning.

1. HTTP Error 403 - access to the server was not authorised, the html could not be grabbed. How frustrating!

2. x.findAll() does not return all result - I was trying to grab 6 'li' containers, but only 4 were ever found by the function. What do?


##HTTP Error 403: Forbidden##

This is related to urllib headers - the website does not want to be wrapped in in dealing with requests from countless scrapers, so requests headed urllib are blocked.

To get around this, you must obscure the fact you are running a scraping bot. The simplest way to do this is by using headers, as follows:

```
req = Request(my_url, headers={'User-Agent': 'Mozilla/5.0'})
page = urlopen(req)
page_html = page.read()
page.close()
```
At first, did this not work for me *(It's `User-Agent` not `User_Agent`, bwap bwap)*.

So here's also another, apparently older solution, from user [Zeta](https://stackoverflow.com/users/678586/zeta) over on [StackOverflow](https://stackoverflow.com/questions/16627227/http-error-403-in-python-3-web-scraping):

```
import urllib.request

class AppURLopener(urllib.request.FancyURLopener):
    version = "Mozilla/5.0"

uClient_opener = AppURLopener()
uClient = uClient_opener.open(my_url)
```
This appears to be a legacy solution, and not preferred. In the end, both solutions worked for me, typos aside.


##x.findAll() does not return all results##


```
product_list = product_categories[x].findAll('li')
```

The above code should have returned 6 results, but I could never get it to go above 4.

Some googling suggested that this was a problem with html_parser. Suggested solution - use html5lib.

This is what parsing the html with BeautifulSoup looked like before:

```
page_soup = soup(page_html, 'html_parser')
product_categories = page_soup.findAll('div', {'class':'category'})
```

The changes to the code are minimal - just replace the html_parser variable with html5lib:

```
import html5lib

page_soup = soup(page_html, 'html5lib')
product_categories = page_soup.findAll('div', {'class':'category'})
```
And it works! `len(product_list)` returns the correct 6 I was looking for.

Hope someone finds this helpful.
Migrating a repository from GitHub into AWS CodeCommit via AWS CLI
Tags: aws, git, cloud, awscodecommit
Published: 2020-12-27 22:41:31

Actually, you can migrate your repository not only from GitHub but also from any **git-based** source control service such as GitLab, BitBucket, Beanstalk (don’t confuse it with AWS Elastic Beanstalk). In order to migrate repository from *non git-based* source control service (such as Subversion, TFS, Perforce) you will have to migrate to a git-based service first. Also you can choose to migrate the whole repository or just some of the branches.

In this article I'll show how to migrate one of GitHub's [AWS Samples repositories](https://github.com/aws-samples/aws-glue-samples) to AWS CodeCommit.

#### Step 1. Create a new repository in AWS CodeCommit

You need to create an empty repository in AWS CodeCommit where you want to migrate a GitHub repository:

```YAML
aws codecommit create-repository --repository-name MyMigratedRepo --repository-description "This is a repo that was migrated from GitHub"
```

#### Step 2. Clone a target repository from GitHub to your local machine

First you need to get a target repository’s url from GitHub:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/g0vxroj9uprum92kojqm.png)


Then run the following commands:

```YAML
# navigate to a directory where you want to save a new repository
cd "{my-full-path-to-destination-folder}"
# clone a repository from GitHub to your local machine
git clone --mirror https://github.com/aws-samples/aws-glue-samples.git myMigrationRepo
```

#### Step 3. Push a cloned repository to AWS CodeCommit

First you need to get a destination repository’s url from AWS CodeCommit:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3i36f48x9dpr6vchyvm7.png)


Then run the following commands
```YAML
git push https://git-codecommit.{my-region}.amazonaws.com/v1/repos/MyMigratedRepo --all
```

#### Step 4. Enjoy the results

Voila! We have just migrated a repository from GitHub into AWS CodeCommit:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lf896jwhjk43f3dp3b9a.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7ksyp9asum0ho2gg3tjx.jpg)